如何通过Windows窗体应用程序启动/停止Windows服务

问题描述:

我希望通过我的WIndows窗体应用程序启动和停止另一个Windows服务应用程序。 我的应用程序的挞我希望启动Windows服务,并在应用程序退出时我希望停止该服务。如何通过Windows窗体应用程序启动/停止Windows服务

这是如何实现的?

您想使用ServiceController class

用你的服务名称初始化它,并调用Start()和Stop()方法。

using System.ServiceProcess; 
ServiceController sc = new ServiceController("My service name"); 
if (sc.Status == ServiceControllerStatus.Stopped) 
{ 
    sc.Start(); 
} 
//etc.. 
+0

我试过但我得到一个拒绝访问异常。 – xaria 2011-05-04 02:55:21

+0

@xaria:您的服务可能需要提升权限才能被控制,在这种情况下,以管理员身份运行您的程序 – CharlesB 2011-05-04 06:49:46

+0

是的,情况就是如此。谢谢 – xaria 2011-05-06 07:32:13