zl程序教程

您现在的位置是:首页 >  系统

当前栏目

启动Windows服务

Windows服务 启动
2023-09-14 08:58:58 时间

实现效果:

  

知识运用:

  ServiceController类的ServiceName Status属性

  public string ServiceName {get; set;}  //对此ServiceController实例引用的服务进行标识的名称

  public ServiceControlerStatus Status {get ;}  //获取由此实例引发的服务的状态   属性为枚举值之一

  

   WaitForStatus  start方法  

  public void Start()  //启动服务

  public void WaitForStatus (ServiceControllerStatus desiredStatus)  //等待服务发到指定状态

实现代码:

        private void button1_Click(object sender, EventArgs e)
        {
            ServiceController sc = new ServiceController();     //创建服务控制对象
            sc.ServiceName = "TermService";                     //启动服务名称
            if (sc.Status == ServiceControllerStatus.Stopped)   //判断服务状态
            {
                try
                {
                    sc.Start();                                 //启动服务
                    sc.WaitForStatus(ServiceControllerStatus.Running);
                }
                catch (InvalidOperationException)
                { MessageBox.Show("该服务不能启动!"); }
            }
        }