C#开启或关闭windows服务

    核心代码

           //   Toggle   the   Telnet   service   -  
            //   If   it   is   started   (running,   paused,   etc),   stop   the   service.
            //   If   it   is   stopped,   start   the   service.
            ServiceController sc = new ServiceController("Telnet");
            MessageBox.Show("The   Telnet   service   status   is   currently   set   to " + sc.Status.ToString());

            if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||(sc.Status.Equals(ServiceControllerStatus.StopPending)))
            {
                //   Start   the   service   if   the   current   status   is   stopped.
                MessageBox.Show("Starting   the   Telnet   service... ");
                sc.Start();
            }
            else
            {
                //   Stop   the   service   if   its   status   is   not   set   to   "Stopped ".
                MessageBox.Show("Stopping   the   Telnet   service... ");
                sc.Stop();
            }

            //   Refresh   and   display   the   current   service   status.
            sc.Refresh();
            MessageBox.Show("The   Telnet   service   status   is   now   set   to "+sc.Status.ToString());

我的程序代码:

namespace 监控服务
{
    public partial class Form1 : Form
    {
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        DateTime startTime;
        TimeSpan span = new TimeSpan();
        public Form1()
        {
            t.Tick += new EventHandler(t_Tick);
            t.Interval = 1000*4;
            InitializeComponent();
        }             

        void t_Tick(object sender, EventArgs e)
        {
            try
            {

                ServiceController sc = new ServiceController("Mamogu.com");
                // MessageBox.Show("The   Telnet   service   status   is   currently   set   to " + sc.Status.ToString());

                if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
                {
                    //   Start   the   service   if   the   current   status   is   stopped.
                    // MessageBox.Show("Starting   the   Telnet   service... ");
                    sc.Start();
                }

                //   Refresh   and   display   the   current   service   status.
                sc.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }      

        private void Form1_Load(object sender, EventArgs e)
        {
            t.Start();
            startTime = DateTime.Now;//在启动时间控件时给初始时间赋值
        }
    }
}

 

posted @ 2010-12-30 14:10  金码  阅读(1077)  评论(0编辑  收藏  举报