C# 開發Windows Service程式控制功能

來源:互聯網
上載者:User

標籤:windows-service   windows服務控   服務控制   

在做一些計劃任務時候難免用到Windows Service服務程式,而這個是沒有操作介面的,每次啟動、重啟、關閉都需要服務介面找到服務進行操作,對普通的人來說是非常麻煩的,所以有時候就需要通過應用程式來控制Windows 服務,這裡把之前寫到的一個服務控制類貼出來。

C# Windows 服務控制類代碼

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceProcess;using System.Threading;namespace Tools.App{    public class ServiceHelper    {        /// <summary>          /// Restart windows service          /// </summary>          /// <param name="serviceName">the windows service display name</param>          /// <returns> If the restart successfully return true else return false</returns>          public static bool RestartWindowsService(string serviceName)        {            bool bResult = false;            try            {                try                {                    StopWindowsService(serviceName);                    Thread.Sleep(1000);                }                catch (Exception ex)                {                    StartWindowsService(serviceName);                    Thread.Sleep(1000);                    StopWindowsService(serviceName);                    Thread.Sleep(1000);                    Console.WriteLine(ex.Message);                }                try                {                    StartWindowsService(serviceName);                    Thread.Sleep(1000);                }                catch (Exception ex)                {                    StopWindowsService(serviceName);                    Thread.Sleep(1000);                    StartWindowsService(serviceName);                    Thread.Sleep(1000);                    Console.WriteLine(ex.Message);                }                bResult = true;            }            catch (Exception ex)            {                bResult = false;                throw ex;            }            return bResult;        }        /// <summary>          /// Start windows service          /// </summary>          /// <param name="serviceName">the windows service display name</param>          /// <returns>If the start successfully return true else return false</returns>          public static bool StopWindowsService(string serviceName)        {            ServiceController[] scs = ServiceController.GetServices();            bool bResult = false;            foreach (ServiceController sc in scs)            {                if (sc.ServiceName == serviceName)                {                    try                    {                        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(1000 * 30));                        sc.Stop();                        bResult = true;                    }                    catch (Exception ex)                    {                        bResult = false;                        throw ex;                    }                }            }            return bResult;        }        /// <summary>          /// Stop windows service          /// </summary>          /// <param name="serviceName">the windows service display name</param>          /// <returns>If the stop successfully return true else return false</returns>          public static bool StartWindowsService(string serviceName)        {            ServiceController[] scs = ServiceController.GetServices();            bool bResult = false;            foreach (ServiceController sc in scs)            {                if (sc.ServiceName == serviceName)                {                    try                    {                        sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(1000 * 30));                        sc.Start();                        bResult = true;                    }                    catch (Exception ex)                    {                        bResult = false;                        throw ex;                    }                }            }            return bResult;        }        public static bool ServiceIsExisted(string serviceName)        {            ServiceController[] services = ServiceController.GetServices();            foreach (ServiceController s in services)            {                if (s.ServiceName == serviceName)                {                    return true;                }            }            return false;        }    }}

表單按鈕事件調用代碼

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.ServiceProcess;using System.Text;using System.Windows.Forms;namespace Tools.App{    public partial class ServiceForm : Form    {        public ServiceForm()        {            InitializeComponent();        }        /// <summary>        /// 載入判斷服務是否存在        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void ServiceForm_Load(object sender, EventArgs e)        {            if (ServiceHelper.ServiceIsExisted("TaskTimer"))            {                ServiceController service = new ServiceController("TaskTimer");                if (service.Status != ServiceControllerStatus.Stopped && service.Status != ServiceControllerStatus.StopPending)                {                    this.btnStart.Enabled = false;                    this.button2.Enabled = true;                }                else                {                    this.btnStart.Enabled = true;                    this.button2.Enabled = false;                }            }        }        /// <summary>        /// 啟動        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnStart_Click(object sender, EventArgs e)        {            ServiceHelper.StartWindowsService("TaskTimer");            this.btnStart.Enabled = false;            this.button2.Enabled = true;            MessageBox.Show("啟動成功", "提示");        }        /// <summary>        /// 關閉        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnClose_Click(object sender, EventArgs e)        {            ServiceHelper.StopWindowsService("TaskTimer");            this.btnStart.Enabled = true;            this.button2.Enabled = false;            MessageBox.Show("關閉成功", "提示");        }        private void btnIsExisted_Click(object sender, EventArgs e)        {            bool bl = ServiceHelper.ServiceIsExisted("TaskTimer");            if (bl)            {                MessageBox.Show("TaskTimer 存在!", "提示");            }            else            {                MessageBox.Show("TaskTimer 不存在!", "提示");            }        }    }}

希望以上分享對初學朋友有些協助,謝謝!
更多關注付義方技術部落格:http://blog.csdn.net/fuyifang
或者直接用手機掃描二維碼查看更多博文:

C# 開發Windows Service程式控制功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.