C#開發可以視覺化操作的windows服務

世紀緣發表於2016-10-28

使用C#開發自定義windows服務是一件十分簡單的事。那麼什麼時候,我們需要自己開發windows服務呢,就是當我們需要計算機定期或者一直執行我們開發的某些程式的時候。這裡我以一個WCF的監聽服務為例,因為我是做一個局域聊天室,需要伺服器端監聽終端,所以我就開發了一個服務,以便控制此監聽服務。然而,我們開發的windows服務,預設情況下是無法視覺化的操作的,這裡我就額外的開發一個工具來對此服務進行操作,效果圖如下:

開發步驟:

1、“新建專案”——“Window服務”

Program.cs程式碼:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Description;  
  7. using System.ServiceProcess;  
  8.   
  9. namespace MSMQChatService  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main()  
  14.         {  
  15.             #region 服務啟動入口,正式用  
  16.   
  17.             ServiceBase[] ServicesToRun;  
  18.             ServicesToRun = new ServiceBase[] {  new MQChatService()  };  
  19.             ServiceBase.Run(ServicesToRun);  
  20.  
  21.             #endregion  
  22.         }  
  23.     }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;

namespace MSMQChatService
{
    class Program
    {
        static void Main()
        {
            #region 服務啟動入口,正式用

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] {  new MQChatService()  };
            ServiceBase.Run(ServicesToRun);

            #endregion
        }
    }

MQChatService.cs程式碼如下:

  1. protected override void OnStart(string[] args)  
  2.         {  
  3.             //開啟服務  這裡就是你想要讓服務做的操作  
  4.             StartService();  
  5.         }  
protected override void OnStart(string[] args)
        {
            //開啟服務  這裡就是你想要讓服務做的操作
            StartService();
        }

3、切換到MQChatService的視覺化介面

4、在視覺化介面,單擊滑鼠右鍵,

將會出現一個Installer為字尾的新介面,預設好像是Project Installer.cs,我這裡將其重新命名為ServiceInstaller.cs

分別對介面上這兩個元件進行屬性配置,具體的屬性簽名可以檢視屬性皮膚的最下面(右下角處)


好了,我們的windows服務已經開發好了,接下來就開發一個視覺化的控制器,來控制服務的安裝、解除安裝、啟動和停止。

1、  新建一個windows程式,名稱ServiceSetup,Form1重新命名為FrmServiceSetup,

介面控制元件如下:


Program.cs程式碼如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7. using System.Windows.Forms;  
  8.   
  9. namespace ServiceSetup  
  10. {  
  11.     static class Program  
  12.     {  
  13.         /// <summary>  
  14.         /// 應用程式的主入口點。  
  15.         /// </summary>  
  16.         [STAThread]  
  17.         static void Main()  
  18.         {  
  19.              //獲取欲啟動程式名  
  20.             string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;  
  21.             ////獲取版本號  
  22.             //CommonData.VersionNumber = Application.ProductVersion;  
  23.             //檢查程式是否已經啟動,已經啟動則顯示報錯資訊退出程式。  
  24.             if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)  
  25.             {  
  26.                 MessageBox.Show("程式已經執行。");  
  27.                 Thread.Sleep(1000);  
  28.                 System.Environment.Exit(1);  
  29.             }  
  30.             else  
  31.             {  
  32.                 Application.EnableVisualStyles();  
  33.                 Application.SetCompatibleTextRenderingDefault(false);  
  34.                 Application.Run(new FrmServiceSetup());  
  35.             }  
  36.         }  
  37.     }  
  38. }  
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServiceSetup
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
             //獲取欲啟動程式名
            string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            ////獲取版本號
            //CommonData.VersionNumber = Application.ProductVersion;
            //檢查程式是否已經啟動,已經啟動則顯示報錯資訊退出程式。
            if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
            {
                MessageBox.Show("程式已經執行。");
                Thread.Sleep(1000);
                System.Environment.Exit(1);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FrmServiceSetup());
            }
        }
    }
}

主介面程式碼:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using System.Windows.Forms;  
  10.   
  11. namespace ServiceSetup  
  12. {  
  13.     public partial class FrmServiceSetup : Form  
  14.     {  
  15.         string strServiceName = string.Empty;  
  16.         public FrmServiceSetup()  
  17.         {  
  18.             InitializeComponent();  
  19.             strServiceName = string.IsNullOrEmpty(lblServiceName.Text) ? "MSMQChatService" : lblServiceName.Text;  
  20.             InitControlStatus(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain);  
  21.         }  
  22.   
  23.         /// <summary>  
  24.         /// 初始化控制元件狀態  
  25.         /// </summary>  
  26.         /// <param name="serviceName">服務名稱</param>  
  27.         /// <param name="btn1">安裝按鈕</param>  
  28.         /// <param name="btn2">啟動按鈕</param>  
  29.         /// <param name="btn3">獲取狀態按鈕</param>  
  30.         /// <param name="txt">提示資訊</param>  
  31.         /// <param name="gb">服務所在組合框</param>  
  32.         void InitControlStatus(string serviceName, Button btn1, Button btn2, Button btn3, Label txt, GroupBox gb)  
  33.         {  
  34.             try  
  35.             {  
  36.                 btn1.Enabled = true;  
  37.   
  38.                 if (ServiceAPI.isServiceIsExisted(serviceName))  
  39.                 {  
  40.                     btn3.Enabled = true;  
  41.                     btn2.Enabled = true;  
  42.                     btn1.Text = "解除安裝服務";  
  43.                     int status = ServiceAPI.GetServiceStatus(serviceName);  
  44.                     if (status == 4)  
  45.                     {  
  46.                         btn2.Text = "停止服務";  
  47.                     }  
  48.                     else  
  49.                     {  
  50.                         btn2.Text = "啟動服務";  
  51.                     }  
  52.                     GetServiceStatus(serviceName, txt);  
  53.                     //獲取服務版本  
  54.                     string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")";  
  55.                     gb.Text += temp;  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     btn1.Text = "安裝服務";  
  60.                     btn2.Enabled = false;  
  61.                     btn3.Enabled = false;  
  62.                     txt.Text = "服務【" + serviceName + "】未安裝!";  
  63.                 }  
  64.             }  
  65.             catch (Exception ex)  
  66.             {  
  67.                 txt.Text = "error";  
  68.                 LogAPI.WriteLog(ex.Message);  
  69.             }  
  70.         }  
  71.   
  72.         /// <summary>  
  73.         /// 安裝或解除安裝服務  
  74.         /// </summary>  
  75.         /// <param name="serviceName">服務名稱</param>  
  76.         /// <param name="btnSet">安裝、解除安裝</param>  
  77.         /// <param name="btnOn">啟動、停止</param>  
  78.         /// <param name="txtMsg">提示資訊</param>  
  79.         /// <param name="gb">組合框</param>  
  80.         void SetServerce(string serviceName, Button btnSet, Button btnOn, Button btnShow, Label txtMsg, GroupBox gb)  
  81.         {  
  82.             try  
  83.             {  
  84.                 string location = System.Reflection.Assembly.GetExecutingAssembly().Location;  
  85.                 string serviceFileName = location.Substring(0, location.LastIndexOf('\\')) + "\\" + serviceName + ".exe";  
  86.   
  87.                 if (btnSet.Text == "安裝服務")  
  88.                 {  
  89.                     ServiceAPI.InstallmyService(null, serviceFileName);  
  90.                     if (ServiceAPI.isServiceIsExisted(serviceName))  
  91.                     {  
  92.                         txtMsg.Text = "服務【" + serviceName + "】安裝成功!";  
  93.                         btnOn.Enabled = btnShow.Enabled = true;  
  94.                         string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")";  
  95.                         gb.Text += temp;  
  96.                         btnSet.Text = "解除安裝服務";  
  97.                         btnOn.Text = "啟動服務";  
  98.                     }  
  99.                     else  
  100.                     {  
  101.                         txtMsg.Text = "服務【" + serviceName + "】安裝失敗,請檢查日誌!";  
  102.                     }  
  103.                 }  
  104.                 else  
  105.                 {  
  106.                     ServiceAPI.UnInstallmyService(serviceFileName);  
  107.                     if (!ServiceAPI.isServiceIsExisted(serviceName))  
  108.                     {  
  109.                         txtMsg.Text = "服務【" + serviceName + "】解除安裝成功!";  
  110.                         btnOn.Enabled = btnShow.Enabled = false;  
  111.                         btnSet.Text = "安裝服務";  
  112.                         //gb.Text =strServiceName;  
  113.                     }  
  114.                     else  
  115.                     {  
  116.                         txtMsg.Text = "服務【" + serviceName + "】解除安裝失敗,請檢查日誌!";  
  117.                     }  
  118.                 }  
  119.             }  
  120.             catch (Exception ex)  
  121.             {  
  122.                 txtMsg.Text = "error";  
  123.                 LogAPI.WriteLog(ex.Message);  
  124.             }  
  125.         }  
  126.   
  127.         //獲取服務狀態  
  128.         void GetServiceStatus(string serviceName, Label txtStatus)  
  129.         {  
  130.             try  
  131.             {  
  132.                 if (ServiceAPI.isServiceIsExisted(serviceName))  
  133.                 {  
  134.                     string statusStr = "";  
  135.                     int status = ServiceAPI.GetServiceStatus(serviceName);  
  136.                     switch (status)  
  137.                     {  
  138.                         case 1:  
  139.                             statusStr = "服務未執行!";  
  140.                             break;  
  141.                         case 2:  
  142.                             statusStr = "服務正在啟動!";  
  143.                             break;  
  144.                         case 3:  
  145.                             statusStr = "服務正在停止!";  
  146.                             break;  
  147.                         case 4:  
  148.                             statusStr = "服務正在執行!";  
  149.                             break;  
  150.                         case 5:  
  151.                             statusStr = "服務即將繼續!";  
  152.                             break;  
  153.                         case 6:  
  154.                             statusStr = "服務即將暫停!";  
  155.                             break;  
  156.                         case 7:  
  157.                             statusStr = "服務已暫停!";  
  158.                             break;  
  159.                         default:  
  160.                             statusStr = "未知狀態!";  
  161.                             break;  
  162.                     }  
  163.                     txtStatus.Text = statusStr;  
  164.                 }  
  165.                 else  
  166.                 {  
  167.                     txtStatus.Text = "服務【" + serviceName + "】未安裝!";  
  168.                 }  
  169.             }  
  170.             catch (Exception ex)  
  171.             {  
  172.                 txtStatus.Text = "error";  
  173.                 LogAPI.WriteLog(ex.Message);  
  174.             }  
  175.         }  
  176.   
  177.         //啟動服務  
  178.         void OnService(string serviceName, Button btn, Label txt)  
  179.         {  
  180.             try  
  181.             {  
  182.                 if (btn.Text == "啟動服務")  
  183.                 {  
  184.                     ServiceAPI.RunService(serviceName);  
  185.   
  186.                     int status = ServiceAPI.GetServiceStatus(serviceName);  
  187.                     if (status == 2 || status == 4 || status == 5)  
  188.                     {  
  189.                         txt.Text = "服務【" + serviceName + "】啟動成功!";  
  190.                         btn.Text = "停止服務";  
  191.                     }  
  192.                     else  
  193.                     {  
  194.                         txt.Text = "服務【" + serviceName + "】啟動失敗!";  
  195.                     }  
  196.                 }  
  197.                 else  
  198.                 {  
  199.                     ServiceAPI.StopService(serviceName);  
  200.   
  201.                     int status = ServiceAPI.GetServiceStatus(serviceName);  
  202.                     if (status == 1 || status == 3 || status == 6 || status == 7)  
  203.                     {  
  204.                         txt.Text = "服務【" + serviceName + "】停止成功!";  
  205.                         btn.Text = "啟動服務";  
  206.                     }  
  207.                     else  
  208.                     {  
  209.                         txt.Text = "服務【" + serviceName + "】停止失敗!";  
  210.                     }  
  211.                 }  
  212.             }  
  213.             catch (Exception ex)  
  214.             {  
  215.                 txt.Text = "error";  
  216.                 LogAPI.WriteLog(ex.Message);  
  217.             }  
  218.         }  
  219.   
  220.         //安裝or解除安裝服務  
  221.         private void btnInstallOrUninstall_Click(object sender, EventArgs e)  
  222.         {  
  223.             btnInstallOrUninstall.Enabled = false;  
  224.             SetServerce(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain);  
  225.             btnInstallOrUninstall.Enabled = true;  
  226.             btnInstallOrUninstall.Focus();  
  227.         }  
  228.   
  229.         //啟動or停止服務  
  230.         private void btnStartOrEnd_Click(object sender, EventArgs e)  
  231.         {  
  232.             btnStartOrEnd.Enabled = false;  
  233.             OnService(strServiceName, btnStartOrEnd, lblMsg);  
  234.             btnStartOrEnd.Enabled = true;  
  235.             btnStartOrEnd.Focus();  
  236.         }  
  237.   
  238.         //獲取服務狀態  
  239.         private void btnGetStatus_Click(object sender, EventArgs e)  
  240.         {  
  241.             btnGetStatus.Enabled = false;  
  242.             GetServiceStatus(strServiceName, lblMsg);  
  243.             btnGetStatus.Enabled = true;  
  244.             btnGetStatus.Focus();  
  245.         }  
  246.   
  247.         private void FrmServiceSetup_Resize(object sender, EventArgs e)  
  248.         {  
  249.             if (this.WindowState == FormWindowState.Minimized)    //最小化到系統托盤  
  250.             {  
  251.                 notifyIcon1.Visible = true;    //顯示托盤圖示  
  252.                 this.ShowInTaskbar = false;  
  253.                 this.Hide();    //隱藏視窗  
  254.             }  
  255.         }  
  256.   
  257.         private void FrmServiceSetup_FormClosing(object sender, FormClosingEventArgs e)  
  258.         {  
  259.             DialogResult result = MessageBox.Show("是縮小到托盤?""確認", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);  
  260.             if (result== DialogResult.Yes)  
  261.             {  
  262.                 // 取消關閉窗體  
  263.                 e.Cancel = true;  
  264.                 // 將窗體變為最小化  
  265.                 this.WindowState = FormWindowState.Minimized;  
  266.             }  
  267.             else if (result == DialogResult.No)  
  268.             {  
  269.                 System.Environment.Exit(0);  
  270.             }  
  271.             else  
  272.             {  
  273.                 e.Cancel = true;  
  274.             }  
  275.         }  
  276.   
  277.         private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)  
  278.         {  
  279.             if (e.Button == MouseButtons.Left&&this.WindowState == FormWindowState.Minimized)  
  280.             {  
  281.                     this.Show();  
  282.                     this.WindowState = FormWindowState.Normal;  
  283.                     this.ShowInTaskbar = true//顯示在系統工作列   
  284.                     //notifyIcon1.Visible = false; //托盤圖示不可見   
  285.                     this.Activate();  
  286.             }  
  287.         }  
  288.   
  289.         private void 開啟主介面ToolStripMenuItem_Click(object sender, EventArgs e)  
  290.         {  
  291.             this.Show();  
  292.             this.WindowState = FormWindowState.Normal;  
  293.             this.ShowInTaskbar = true//顯示在系統工作列   
  294.             notifyIcon1.Visible = false//托盤圖示不可見   
  295.             this.Activate();  
  296.         }  
  297.   
  298.         private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)  
  299.         {  
  300.             System.Environment.Exit(0);    
  301.             ExitProcess();  
  302.         }  
  303.            //結束程式  
  304.         private void ExitProcess()  
  305.         {  
  306.             System.Environment.Exit(0);  
  307.             Process[] ps = Process.GetProcesses();  
  308.             foreach (Process item in ps)  
  309.             {  
  310.                 if (item.ProcessName == "ServiceSetup")  
  311.                 {  
  312.                     item.Kill();  
  313.                 }  
  314.             }  
  315.         }  
  316.  }  
  317. }  
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServiceSetup
{
    public partial class FrmServiceSetup : Form
    {
        string strServiceName = string.Empty;
        public FrmServiceSetup()
        {
            InitializeComponent();
            strServiceName = string.IsNullOrEmpty(lblServiceName.Text) ? "MSMQChatService" : lblServiceName.Text;
            InitControlStatus(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain);
        }

        /// <summary>
        /// 初始化控制元件狀態
        /// </summary>
        /// <param name="serviceName">服務名稱</param>
        /// <param name="btn1">安裝按鈕</param>
        /// <param name="btn2">啟動按鈕</param>
        /// <param name="btn3">獲取狀態按鈕</param>
        /// <param name="txt">提示資訊</param>
        /// <param name="gb">服務所在組合框</param>
        void InitControlStatus(string serviceName, Button btn1, Button btn2, Button btn3, Label txt, GroupBox gb)
        {
            try
            {
                btn1.Enabled = true;

                if (ServiceAPI.isServiceIsExisted(serviceName))
                {
                    btn3.Enabled = true;
                    btn2.Enabled = true;
                    btn1.Text = "解除安裝服務";
                    int status = ServiceAPI.GetServiceStatus(serviceName);
                    if (status == 4)
                    {
                        btn2.Text = "停止服務";
                    }
                    else
                    {
                        btn2.Text = "啟動服務";
                    }
                    GetServiceStatus(serviceName, txt);
                    //獲取服務版本
                    string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")";
                    gb.Text += temp;
                }
                else
                {
                    btn1.Text = "安裝服務";
                    btn2.Enabled = false;
                    btn3.Enabled = false;
                    txt.Text = "服務【" + serviceName + "】未安裝!";
                }
            }
            catch (Exception ex)
            {
                txt.Text = "error";
                LogAPI.WriteLog(ex.Message);
            }
        }

        /// <summary>
        /// 安裝或解除安裝服務
        /// </summary>
        /// <param name="serviceName">服務名稱</param>
        /// <param name="btnSet">安裝、解除安裝</param>
        /// <param name="btnOn">啟動、停止</param>
        /// <param name="txtMsg">提示資訊</param>
        /// <param name="gb">組合框</param>
        void SetServerce(string serviceName, Button btnSet, Button btnOn, Button btnShow, Label txtMsg, GroupBox gb)
        {
            try
            {
                string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string serviceFileName = location.Substring(0, location.LastIndexOf('\\')) + "\\" + serviceName + ".exe";

                if (btnSet.Text == "安裝服務")
                {
                    ServiceAPI.InstallmyService(null, serviceFileName);
                    if (ServiceAPI.isServiceIsExisted(serviceName))
                    {
                        txtMsg.Text = "服務【" + serviceName + "】安裝成功!";
                        btnOn.Enabled = btnShow.Enabled = true;
                        string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")";
                        gb.Text += temp;
                        btnSet.Text = "解除安裝服務";
                        btnOn.Text = "啟動服務";
                    }
                    else
                    {
                        txtMsg.Text = "服務【" + serviceName + "】安裝失敗,請檢查日誌!";
                    }
                }
                else
                {
                    ServiceAPI.UnInstallmyService(serviceFileName);
                    if (!ServiceAPI.isServiceIsExisted(serviceName))
                    {
                        txtMsg.Text = "服務【" + serviceName + "】解除安裝成功!";
                        btnOn.Enabled = btnShow.Enabled = false;
                        btnSet.Text = "安裝服務";
                        //gb.Text =strServiceName;
                    }
                    else
                    {
                        txtMsg.Text = "服務【" + serviceName + "】解除安裝失敗,請檢查日誌!";
                    }
                }
            }
            catch (Exception ex)
            {
                txtMsg.Text = "error";
                LogAPI.WriteLog(ex.Message);
            }
        }

        //獲取服務狀態
        void GetServiceStatus(string serviceName, Label txtStatus)
        {
            try
            {
                if (ServiceAPI.isServiceIsExisted(serviceName))
                {
                    string statusStr = "";
                    int status = ServiceAPI.GetServiceStatus(serviceName);
                    switch (status)
                    {
                        case 1:
                            statusStr = "服務未執行!";
                            break;
                        case 2:
                            statusStr = "服務正在啟動!";
                            break;
                        case 3:
                            statusStr = "服務正在停止!";
                            break;
                        case 4:
                            statusStr = "服務正在執行!";
                            break;
                        case 5:
                            statusStr = "服務即將繼續!";
                            break;
                        case 6:
                            statusStr = "服務即將暫停!";
                            break;
                        case 7:
                            statusStr = "服務已暫停!";
                            break;
                        default:
                            statusStr = "未知狀態!";
                            break;
                    }
                    txtStatus.Text = statusStr;
                }
                else
                {
                    txtStatus.Text = "服務【" + serviceName + "】未安裝!";
                }
            }
            catch (Exception ex)
            {
                txtStatus.Text = "error";
                LogAPI.WriteLog(ex.Message);
            }
        }

        //啟動服務
        void OnService(string serviceName, Button btn, Label txt)
        {
            try
            {
                if (btn.Text == "啟動服務")
                {
                    ServiceAPI.RunService(serviceName);

                    int status = ServiceAPI.GetServiceStatus(serviceName);
                    if (status == 2 || status == 4 || status == 5)
                    {
                        txt.Text = "服務【" + serviceName + "】啟動成功!";
                        btn.Text = "停止服務";
                    }
                    else
                    {
                        txt.Text = "服務【" + serviceName + "】啟動失敗!";
                    }
                }
                else
                {
                    ServiceAPI.StopService(serviceName);

                    int status = ServiceAPI.GetServiceStatus(serviceName);
                    if (status == 1 || status == 3 || status == 6 || status == 7)
                    {
                        txt.Text = "服務【" + serviceName + "】停止成功!";
                        btn.Text = "啟動服務";
                    }
                    else
                    {
                        txt.Text = "服務【" + serviceName + "】停止失敗!";
                    }
                }
            }
            catch (Exception ex)
            {
                txt.Text = "error";
                LogAPI.WriteLog(ex.Message);
            }
        }

        //安裝or解除安裝服務
        private void btnInstallOrUninstall_Click(object sender, EventArgs e)
        {
            btnInstallOrUninstall.Enabled = false;
            SetServerce(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain);
            btnInstallOrUninstall.Enabled = true;
            btnInstallOrUninstall.Focus();
        }

        //啟動or停止服務
        private void btnStartOrEnd_Click(object sender, EventArgs e)
        {
            btnStartOrEnd.Enabled = false;
            OnService(strServiceName, btnStartOrEnd, lblMsg);
            btnStartOrEnd.Enabled = true;
            btnStartOrEnd.Focus();
        }

        //獲取服務狀態
        private void btnGetStatus_Click(object sender, EventArgs e)
        {
            btnGetStatus.Enabled = false;
            GetServiceStatus(strServiceName, lblMsg);
            btnGetStatus.Enabled = true;
            btnGetStatus.Focus();
        }

        private void FrmServiceSetup_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系統托盤
            {
                notifyIcon1.Visible = true;    //顯示托盤圖示
                this.ShowInTaskbar = false;
                this.Hide();    //隱藏視窗
            }
        }

        private void FrmServiceSetup_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("是縮小到托盤?", "確認", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
            if (result== DialogResult.Yes)
            {
                // 取消關閉窗體
                e.Cancel = true;
                // 將窗體變為最小化
                this.WindowState = FormWindowState.Minimized;
            }
            else if (result == DialogResult.No)
            {
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left&&this.WindowState == FormWindowState.Minimized)
            {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    this.ShowInTaskbar = true; //顯示在系統工作列 
                    //notifyIcon1.Visible = false; //托盤圖示不可見 
                    this.Activate();
            }
        }

        private void 開啟主介面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true; //顯示在系統工作列 
            notifyIcon1.Visible = false; //托盤圖示不可見 
            this.Activate();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);  
            ExitProcess();
        }
           //結束程式
        private void ExitProcess()
        {
            System.Environment.Exit(0);
            Process[] ps = Process.GetProcesses();
            foreach (Process item in ps)
            {
                if (item.ProcessName == "ServiceSetup")
                {
                    item.Kill();
                }
            }
        }
 }
}

新建一個類,專門用於日誌操作LogAPI.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace ServiceSetup  
  9. {  
  10.     public class LogAPI  
  11.     {  
  12.         private static string myPath = "";  
  13.         private static string myName = "";  
  14.   
  15.         /// <summary>  
  16.         /// 初始化日誌檔案  
  17.         /// </summary>  
  18.         /// <param name="logPath"></param>  
  19.         /// <param name="logName"></param>  
  20.         public static void InitLogAPI(string logPath, string logName)  
  21.         {  
  22.             myPath = logPath;  
  23.             myName = logName;  
  24.         }  
  25.   
  26.         /// <summary>  
  27.         /// 寫入日誌  
  28.         /// </summary>  
  29.         /// <param name="ex">日誌資訊</param>  
  30.         public static void WriteLog(string ex)  
  31.         {  
  32.             if (myPath == "" || myName == "")  
  33.                 return;  
  34.   
  35.             string Year = DateTime.Now.Year.ToString();  
  36.             string Month = DateTime.Now.Month.ToString().PadLeft(2, '0');  
  37.             string Day = DateTime.Now.Day.ToString().PadLeft(2, '0');  
  38.   
  39.             //年月日資料夾是否存在,不存在則建立  
  40.             if (!Directory.Exists(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day))  
  41.             {  
  42.                 Directory.CreateDirectory(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day);  
  43.             }  
  44.   
  45.             //寫入日誌UNDO,Exception has not been handle  
  46.             string LogFile = myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day + "\\" + myName;  
  47.             if (!File.Exists(LogFile))  
  48.             {  
  49.                 System.IO.StreamWriter myFile;  
  50.                 myFile = System.IO.File.AppendText(LogFile);  
  51.                 myFile.Close();  
  52.             }  
  53.   
  54.             while (true)  
  55.             {  
  56.                 try  
  57.                 {  
  58.                     StreamWriter sr = File.AppendText(LogFile);  
  59.                     sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "  " + ex);  
  60.                     sr.Close();  
  61.                     break;  
  62.                 }  
  63.                 catch (Exception e)  
  64.                 {  
  65.                     System.Threading.Thread.Sleep(50);  
  66.                     continue;  
  67.                 }  
  68.             }  
  69.   
  70.         }  
  71.   
  72.     }  
  73. }  
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceSetup
{
    public class LogAPI
    {
        private static string myPath = "";
        private static string myName = "";

        /// <summary>
        /// 初始化日誌檔案
        /// </summary>
        /// <param name="logPath"></param>
        /// <param name="logName"></param>
        public static void InitLogAPI(string logPath, string logName)
        {
            myPath = logPath;
            myName = logName;
        }

        /// <summary>
        /// 寫入日誌
        /// </summary>
        /// <param name="ex">日誌資訊</param>
        public static void WriteLog(string ex)
        {
            if (myPath == "" || myName == "")
                return;

            string Year = DateTime.Now.Year.ToString();
            string Month = DateTime.Now.Month.ToString().PadLeft(2, '0');
            string Day = DateTime.Now.Day.ToString().PadLeft(2, '0');

            //年月日資料夾是否存在,不存在則建立
            if (!Directory.Exists(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day))
            {
                Directory.CreateDirectory(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day);
            }

            //寫入日誌UNDO,Exception has not been handle
            string LogFile = myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day + "\\" + myName;
            if (!File.Exists(LogFile))
            {
                System.IO.StreamWriter myFile;
                myFile = System.IO.File.AppendText(LogFile);
                myFile.Close();
            }

            while (true)
            {
                try
                {
                    StreamWriter sr = File.AppendText(LogFile);
                    sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "  " + ex);
                    sr.Close();
                    break;
                }
                catch (Exception e)
                {
                    System.Threading.Thread.Sleep(50);
                    continue;
                }
            }

        }

    }
}
Windows服務的操作類ServiceAPI.cs
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Configuration.Install;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Reflection;  
  8. using System.ServiceProcess;  
  9. using System.Text;  
  10. using System.Threading.Tasks;  
  11. using Microsoft.Win32;  
  12.   
  13. namespace ServiceSetup  
  14. {  
  15.     public class ServiceAPI  
  16.     {  
  17.         /// <summary>  
  18.         /// 檢查服務存在的存在性  
  19.         /// </summary>  
  20.         /// <param name=" NameService ">服務名</param>  
  21.         /// <returns>存在返回 true,否則返回 false;</returns>  
  22.         public static bool isServiceIsExisted(string NameService)  
  23.         {  
  24.             ServiceController[] services = ServiceController.GetServices();  
  25.             foreach (ServiceController s in services)  
  26.             {  
  27.                 if (s.ServiceName.ToLower() == NameService.ToLower())  
  28.                 {  
  29.                     return true;  
  30.                 }  
  31.             }  
  32.             return false;  
  33.         }  
  34.         /// <summary>  
  35.         /// 安裝Windows服務  
  36.         /// </summary>  
  37.         /// <param name="stateSaver">集合</param>  
  38.         /// <param name="filepath">程式檔案路徑</param>  
  39.         public static void InstallmyService(IDictionary stateSaver, string filepath)  
  40.         {  
  41.             AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();  
  42.             AssemblyInstaller1.UseNewContext = true;  
  43.             AssemblyInstaller1.Path = filepath;  
  44.             AssemblyInstaller1.Install(stateSaver);  
  45.             AssemblyInstaller1.Commit(stateSaver);  
  46.             AssemblyInstaller1.Dispose();  
  47.         }  
  48.         /// <summary>  
  49.         /// 解除安裝Windows服務  
  50.         /// </summary>  
  51.         /// <param name="filepath">程式檔案路徑</param>  
  52.         public static void UnInstallmyService(string filepath)  
  53.         {  
  54.             AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();  
  55.             AssemblyInstaller1.UseNewContext = true;  
  56.             AssemblyInstaller1.Path = filepath;  
  57.             AssemblyInstaller1.Uninstall(null);  
  58.             AssemblyInstaller1.Dispose();  
  59.         }  
  60.   
  61.         /// <summary>  
  62.         /// 啟動服務  
  63.         /// </summary>  
  64.         /// <param name=" NameService ">服務名</param>  
  65.         /// <returns>存在返回 true,否則返回 false;</returns>  
  66.         public static bool RunService(string NameService)  
  67.         {  
  68.             bool bo = true;  
  69.             try  
  70.             {  
  71.                 ServiceController sc = new ServiceController(NameService);  
  72.                 if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending))  
  73.                 {  
  74.                     sc.Start();  
  75.                 }  
  76.             }  
  77.             catch (Exception ex)  
  78.             {  
  79.                 bo = false;  
  80.                 LogAPI.WriteLog(ex.Message);  
  81.             }  
  82.   
  83.             return bo;  
  84.         }  
  85.   
  86.         /// <summary>  
  87.         /// 停止服務  
  88.         /// </summary>  
  89.         /// <param name=" NameService ">服務名</param>  
  90.         /// <returns>存在返回 true,否則返回 false;</returns>  
  91.         public static bool StopService(string NameService)  
  92.         {  
  93.             bool bo = true;  
  94.             try  
  95.             {  
  96.                 ServiceController sc = new ServiceController(NameService);  
  97.                 if (!sc.Status.Equals(ServiceControllerStatus.Stopped))  
  98.                 {  
  99.                     sc.Stop();  
  100.                 }  
  101.             }  
  102.             catch (Exception ex)  
  103.             {  
  104.                 bo = false;  
  105.                 LogAPI.WriteLog(ex.Message);  
  106.             }  
  107.   
  108.             return bo;  
  109.         }  
  110.   
  111.         /// <summary>  
  112.         /// 獲取服務狀態  
  113.         /// </summary>  
  114.         /// <param name=" NameService ">服務名</param>  
  115.         /// <returns>返回服務狀態</returns>  
  116.         public static int GetServiceStatus(string NameService)  
  117.         {  
  118.             int ret = 0;  
  119.             try  
  120.             {  
  121.                 ServiceController sc = new ServiceController(NameService);  
  122.                 ret = Convert.ToInt16(sc.Status);  
  123.             }  
  124.             catch (Exception ex)  
  125.             {  
  126.                 ret = 0;  
  127.                 LogAPI.WriteLog(ex.Message);  
  128.             }  
  129.   
  130.             return ret;  
  131.         }  
  132.   
  133.         /// <summary>  
  134.         /// 獲取服務安裝路徑  
  135.         /// </summary>  
  136.         /// <param name="ServiceName"></param>  
  137.         /// <returns></returns>  
  138.         public static string GetWindowsServiceInstallPath(string ServiceName)  
  139.         {  
  140.             string path = "";  
  141.             try  
  142.             {  
  143.                 string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;  
  144.                 path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();  
  145.   
  146.                 path = path.Replace("\""string.Empty);//替換掉雙引號    
  147.   
  148.                 FileInfo fi = new FileInfo(path);  
  149.                 path = fi.Directory.ToString();  
  150.             }  
  151.             catch (Exception ex)  
  152.             {  
  153.                 path = "";  
  154.                 LogAPI.WriteLog(ex.Message);  
  155.             }  
  156.             return path;  
  157.         }  
  158.   
  159.         /// <summary>  
  160.         /// 獲取指定服務的版本號  
  161.         /// </summary>  
  162.         /// <param name="serviceName">服務名稱</param>  
  163.         /// <returns></returns>  
  164.         public static string GetServiceVersion(string serviceName)  
  165.         {  
  166.             if (string.IsNullOrEmpty(serviceName))  
  167.             {  
  168.                 return string.Empty;  
  169.             }  
  170.             try  
  171.             {  
  172.                 string path = GetWindowsServiceInstallPath(serviceName) + "\\" + serviceName + ".exe";  
  173.                 Assembly assembly = Assembly.LoadFile(path);  
  174.                 AssemblyName assemblyName = assembly.GetName();  
  175.                 Version version = assemblyName.Version;  
  176.                 return version.ToString();  
  177.             }  
  178.             catch (Exception ex)  
  179.             {  
  180.                 LogAPI.WriteLog(ex.Message);  
  181.                 return string.Empty;  
  182.             }  
  183.         }  
  184.     }  
  185. }  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace ServiceSetup
{
    public class ServiceAPI
    {
        /// <summary>
        /// 檢查服務存在的存在性
        /// </summary>
        /// <param name=" NameService ">服務名</param>
        /// <returns>存在返回 true,否則返回 false;</returns>
        public static bool isServiceIsExisted(string NameService)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == NameService.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 安裝Windows服務
        /// </summary>
        /// <param name="stateSaver">集合</param>
        /// <param name="filepath">程式檔案路徑</param>
        public static void InstallmyService(IDictionary stateSaver, string filepath)
        {
            AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
            AssemblyInstaller1.UseNewContext = true;
            AssemblyInstaller1.Path = filepath;
            AssemblyInstaller1.Install(stateSaver);
            AssemblyInstaller1.Commit(stateSaver);
            AssemblyInstaller1.Dispose();
        }
        /// <summary>
        /// 解除安裝Windows服務
        /// </summary>
        /// <param name="filepath">程式檔案路徑</param>
        public static void UnInstallmyService(string filepath)
        {
            AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
            AssemblyInstaller1.UseNewContext = true;
            AssemblyInstaller1.Path = filepath;
            AssemblyInstaller1.Uninstall(null);
            AssemblyInstaller1.Dispose();
        }

        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name=" NameService ">服務名</param>
        /// <returns>存在返回 true,否則返回 false;</returns>
        public static bool RunService(string NameService)
        {
            bool bo = true;
            try
            {
                ServiceController sc = new ServiceController(NameService);
                if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending))
                {
                    sc.Start();
                }
            }
            catch (Exception ex)
            {
                bo = false;
                LogAPI.WriteLog(ex.Message);
            }

            return bo;
        }

        /// <summary>
        /// 停止服務
        /// </summary>
        /// <param name=" NameService ">服務名</param>
        /// <returns>存在返回 true,否則返回 false;</returns>
        public static bool StopService(string NameService)
        {
            bool bo = true;
            try
            {
                ServiceController sc = new ServiceController(NameService);
                if (!sc.Status.Equals(ServiceControllerStatus.Stopped))
                {
                    sc.Stop();
                }
            }
            catch (Exception ex)
            {
                bo = false;
                LogAPI.WriteLog(ex.Message);
            }

            return bo;
        }

        /// <summary>
        /// 獲取服務狀態
        /// </summary>
        /// <param name=" NameService ">服務名</param>
        /// <returns>返回服務狀態</returns>
        public static int GetServiceStatus(string NameService)
        {
            int ret = 0;
            try
            {
                ServiceController sc = new ServiceController(NameService);
                ret = Convert.ToInt16(sc.Status);
            }
            catch (Exception ex)
            {
                ret = 0;
                LogAPI.WriteLog(ex.Message);
            }

            return ret;
        }

        /// <summary>
        /// 獲取服務安裝路徑
        /// </summary>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string GetWindowsServiceInstallPath(string ServiceName)
        {
            string path = "";
            try
            {
                string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;
                path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();

                path = path.Replace("\"", string.Empty);//替換掉雙引號  

                FileInfo fi = new FileInfo(path);
                path = fi.Directory.ToString();
            }
            catch (Exception ex)
            {
                path = "";
                LogAPI.WriteLog(ex.Message);
            }
            return path;
        }

        /// <summary>
        /// 獲取指定服務的版本號
        /// </summary>
        /// <param name="serviceName">服務名稱</param>
        /// <returns></returns>
        public static string GetServiceVersion(string serviceName)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                return string.Empty;
            }
            try
            {
                string path = GetWindowsServiceInstallPath(serviceName) + "\\" + serviceName + ".exe";
                Assembly assembly = Assembly.LoadFile(path);
                AssemblyName assemblyName = assembly.GetName();
                Version version = assemblyName.Version;
                return version.ToString();
            }
            catch (Exception ex)
            {
                LogAPI.WriteLog(ex.Message);
                return string.Empty;
            }
        }
    }
}
注意:記得將服務程式的dll拷貝到視覺化安裝程式的bin目錄下面.

相關文章