从表单应用程序启动停止服务c#

Ale*_*ruC 36 .net c# windows-services

如何从ac#Form应用程序启动和停止Windows服务?

Joh*_*ner 67

添加引用System.ServiceProcess.dll.然后,您可以使用ServiceController类.

// 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.");
   }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ers 23

首先添加对System.ServiceProcess程序集的引用.

开始:

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

停止:

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

这两个示例都显示了如何等待服务达到新状态(运行,停止等等).WaitForStatus中的timeout参数是可选的.