从表格附录C#启动停止服务 [英] Start stop Service from Form App c#

查看:113
本文介绍了从表格附录C#启动停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何启动和停止从C#窗体应用程序Windows服务?

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

推荐答案

添加一个引用到 System.ServiceProcess.dll 。然后你可以使用 ServiceController的类。

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.");
   }
}

这篇关于从表格附录C#启动停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆