手把手教用C#編寫Windows服務 並控制服務 安裝、啟動、停止、卸載


Windows服務

Microsoft Windows 服務(即,以前的 NT 服務)使您能夠創建在它們自己的 Windows 會話中可長時間運行的可執行應用程序。這些服務可以在計算機啟動時自動啟動,可以暫停和重新啟動而且不顯示任何用戶界面。這種服務非常適合在服務器上使用,或任何時候,為了不影響在同一台計算機上工作的其他用戶,需要長時間運行功能時使用。還可以在不同於登錄用戶的特定用戶帳戶或默認計算機帳戶的安全上下文中運行服務。

創建Windows服務應用程序 即創建 Windows窗體應用程序 項目

 

然后再項目上添加新建項

 

選中Windows服務文件 出現設計界面后 在界面任意位置右鍵  添加安裝程序

 

出現如下安裝界面

 

選中 serviceInstaller 按 F4 可更改服務屬性

Description :服務描述

DisplayName :服務顯示名稱

ServiceName :服務的真實名稱

StartType :服務的 啟動 類型 【手動啟動、自動啟動、禁用】

 

選中 serviceProcessInstaller 按 F4 設置服務的 登錄 類型

 

在 MyService.cs 文件中寫 服務啟動 和 停止 分別 執行的 代碼

最后在 Program Main() 方法中 寫調用服務的 代碼

以上操作就可以成功編寫一個 Windows服務 了

 

繼續,我們對 Windows 服務 進行安裝

仍然創建一個 Windows 窗體應用程序 對剛創建的服務 進行操作【安裝 、啟動 、停止 、卸載】

 

 

 

using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms;

namespace WindowsServiceInstallProgram
{
    public partial class ServicePacageInstall : Form
    {
        public ServicePacageInstall()
        {
            InitializeComponent();
        }

        string serviceProgramPath = Application.StartupPath + "\\MyService.exe";//安裝服務路徑
        string serviceName = "ownService";//安裝服務名稱 非 服務顯示 名稱

        /// <summary>
        /// 安裝服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInstallService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    UninstallService(serviceProgramPath);
                }
                InstallService(serviceProgramPath);
                MessageBox.Show(
                    string.Format("服務【{0}】安裝成功!\r\n時間:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服務【{0}】安裝失敗!\r\n錯誤信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }

        }

        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLaunchService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    LaunchService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服務【{0}】成功啟動!\r\n時間:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服務【{0}】啟動失敗!\r\n錯誤信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 停止服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    StopService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服務【{0}】成功停止!\r\n時間:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服務【{0}】停止失敗!\r\n錯誤信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 卸載服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUninstallService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    StopService(serviceName);
                    UninstallService(serviceProgramPath);
                    MessageBox.Show(
                        string.Format("服務【{0}】成功卸載!\r\n時間:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(
                        string.Format("服務【{0}】不存在!\r\n時間:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服務【{0}】卸載失敗!\r\n錯誤信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        #region 判斷服務是否存在
        private bool IsExistsService(string serviceName)
        {
            /* 另一種方法
            得到當前計算機所有服務對象
            serviceController[] serviceControllers = ServiceController.GetServices();
            通過服務名【ServiceName】(非顯示服務名DisplayServiceName) 得到服務對象①
            ServiceController serviceController = serviceControllers.SingleOrDefault(s => s.ServiceName == serviceName);
            */
            foreach (ServiceController sc in ServiceController.GetServices())
            {
                if (sc.ServiceName.ToUpper() == serviceName.ToUpper())
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 安裝服務
        private void InstallService(string serviceProgramPath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceProgramPath;
                IDictionary saveState = new Hashtable();
                installer.Install(saveState);
                installer.Commit(saveState);
            }
        }
        #endregion

        #region 啟動服務
        private void LaunchService(string serviceName)
        {
            using (ServiceController currentService = new ServiceController(serviceName))
            {
                if (currentService.Status == ServiceControllerStatus.Stopped)
                {
                    currentService.Start();
                }
            }
        }
        #endregion

        #region 停止服務
        private void StopService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                }
            }
        }
        #endregion

        #region 卸載服務
        private void UninstallService(string serviceProgramPath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = this.serviceProgramPath;
                installer.Uninstall(null);
            }
        }
        #endregion
    }
}

 

記得用管理員身份運行起來,否則會操作 失敗的

未用管理員權限運行結果

 

 管理員權限運行結果 如下

 

效果如下

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM