How to send a custom command to a .NET windows Service from .NET code?

You can send “commands” to a service using ServiceController.ExecuteCommand:

const int SmartRestart = 222;

var service = new System.ServiceProcess.ServiceController("MyService");
service.WaitForStatus(ServiceControllerStatus.Running, timeout);

You’ll need to add a Reference to the System.ServiceProcess.dll assembly.

The service can react to the command by overriding ServiceBase.OnCustomCommand:

protected override void OnCustomCommand(int command)
    if (command == SmartRestart)
        // ...

Leave a Comment