How to start and stop the any window service in the windows operating system using windows app

The linked answer shows how to start and stop services. First, create an instance of the ServicesController class, passing the name of the service. You can use the controller to control the service by calling its methods, eg Start to start it, Stop to stop it.

Services don’t start or stop instantly, so you should probably warn the user if it takes too long.

Try this:

    private void start_Click(object sender, EventArgs e)
    {
        string serviceName = "yourServiceName";
        double timeoutMilliseconds = 10_000;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);   
        
        ServiceController service = new ServiceController(serviceName);
        try
        {
            service.Start();                
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
        catch(InvalidOperationException exc)
        {
            MessageBox.Show($"The service failed to start in a timely manner\n\n{exc}");                
        }
    }

    private void stop_Click(object sender, EventArgs e)
    {
        string serviceName = "yourServiceName";
        double timeoutMilliseconds = 10_000;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        ServiceController service = new ServiceController(serviceName);
        try
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }
        catch(InvalidOperationException exc)
        {
            MessageBox.Show($"The service failed to start in a timely manner\n\n{exc}");                
        }
    }

Leave a Comment