c#编写一个winform 管理一个windows服务

使用c#编写一个winform程序, 管理一个windows服务。对指定的windows服务,进行启动、停止、重新启动

1、引入 using System.ServiceProcess;

2、

  /// <summary>
        /// 重新启动按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopAndRun_Click(object sender, EventArgs e)
        {
            ServiceController serviceObject = this.GetServiceObject();
            try
            {
                this.ReStarService(serviceObject);
                MessageBox.Show("重启服务成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("重启服务错误:" + ex.Message.ToString());
            }
        }

        //获取windows服务实例
        private ServiceController GetServiceObject()
        {
            return new ServiceController("FloatcarGpsAppServer");
        }
        /// <summary>
        /// 重启
        /// </summary>
        /// <param name="sc"></param>
        private void ReStarService(ServiceController sc)
        {
            this.StopService(sc);
            this.StarService(sc);
        }
        /// <summary>
        ///  停止服务
        /// </summary>
        /// <param name="sc"></param>
        private void StopService(ServiceController sc)
        {
            if ((sc.Status == ServiceControllerStatus.Paused) || (sc.Status == ServiceControllerStatus.Running))
            {
                sc.Stop();
            }
        }
        /// <summary>
        /// 开始服务
        /// </summary>
        /// <param name="sc"></param>
        private void StarService(ServiceController sc)
        {
            if ((sc.Status == ServiceControllerStatus.Paused) || (sc.Status == ServiceControllerStatus.Stopped))
            {
                sc.Start();
            }
        }
        /// <summary>
        /// 停止服务按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            ServiceController serviceObject = this.GetServiceObject();
            try
            {
                this.StopService(serviceObject);
                MessageBox.Show("停止服务成功!");
            }
            catch (Exception ex)
            {

                MessageBox.Show("停止服务发生错误:" + ex.Message.ToString());
            }
        }
        /// <summary>
        /// 开始服务按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRun_Click(object sender, EventArgs e)
        {
            ServiceController serviceObject = this.GetServiceObject();
            try
            {
                this.StarService(serviceObject);
                MessageBox.Show("启动服务成功!");
            }
            catch (Exception  ex)
            {

                MessageBox.Show("启动服务失败:" + ex.Message);
            }
        }
原文地址:https://www.cnblogs.com/huacw/p/2106129.html