使用ServiceController控制windows服务

ServiceController控制windows服务

1.在项目中“引用”=》.net选项中找到System.ServiceProcess

2.using System.ServiceProcess;

//启动服务

        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceController sc = new ServiceController("WapSearchWCFService");
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running);
                }
                sc.Close();
                this.label27.Text = "已启动";
            }
            catch
            {
                MessageBox.Show("启动失败!");
            }
        }


//停止服务

        private void button14_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceController sc = new ServiceController("WapSearchWCFService");
                if (sc.Status == ServiceControllerStatus.Running)
                {
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped);
                }
                sc.Close();
                this.label27.Text = "已停止";
            }
            catch
            {
                MessageBox.Show("停止失败!");
            }
        }


 

//重新启动

 private void button15_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceController sc = new ServiceController("WapSearchWCFService");
                if (sc.Status == ServiceControllerStatus.Running)
                {
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped);
                    this.label27.Text = "已停止";
                }
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running);
                    this.label27.Text = "已启动";
                }
                sc.Close();
                MessageBox.Show("重新启动成功!");
            }
            catch
            {
                MessageBox.Show("重新启动失败!");
            }
        }


 

 


 

使用ServiceController控制windows服务

上一篇:JavaScript Window Location 几个实例


下一篇:windows下面遍历目录下所有的文件