Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start stop Service from Form App c#

How can I start and stop a windows service from a c# Form application?

like image 652
AlexandruC Avatar asked Jun 16 '12 11:06

AlexandruC


People also ask

Which ServiceController method can be used to send a command to the service in C#?

ExecuteCommand(Int32) Method.


2 Answers

Add a reference to System.ServiceProcess.dll. Then you can use the ServiceController class.

// Check whether the Alerter service is started. ServiceController sc  = new ServiceController(); sc.ServiceName = "Alerter"; Console.WriteLine("The Alerter service status is currently set to {0}",                     sc.Status.ToString());  if (sc.Status == ServiceControllerStatus.Stopped) {    // Start the service if the current status is stopped.    Console.WriteLine("Starting the Alerter service...");    try     {       // Start the service, and wait until its status is "Running".       sc.Start();       sc.WaitForStatus(ServiceControllerStatus.Running);        // Display the current service status.       Console.WriteLine("The Alerter service status is now set to {0}.",                           sc.Status.ToString());    }    catch (InvalidOperationException)    {       Console.WriteLine("Could not start the Alerter service.");    } } 
like image 81
John Koerner Avatar answered Sep 23 '22 01:09

John Koerner


First add a reference to the System.ServiceProcess assembly.

To start:

ServiceController service = new ServiceController("YourServiceName"); service.Start(); var timeout = new TimeSpan(0, 0, 5); // 5seconds service.WaitForStatus(ServiceControllerStatus.Running, timeout); 

To stop:

ServiceController service = new ServiceController("YourServiceName"); service.Stop();  var timeout = new TimeSpan(0, 0, 5); // 5seconds service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); 

Both examples show how to wait until the service has reached a new status (running, stopped...etc.). The timeout parameter in WaitForStatus is optional.

like image 25
Christophe Geers Avatar answered Sep 19 '22 01:09

Christophe Geers