溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用C#編寫一個(gè)Windows服務(wù)程序

發(fā)布時(shí)間:2023-03-14 09:46:24 來源:億速云 閱讀:162 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下如何用C#編寫一個(gè)Windows服務(wù)程序的相關(guān)知識點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

1.添加引用Windows服務(wù)(.NET Framework)

如何用C#編寫一個(gè)Windows服務(wù)程序

2.輸入項(xiàng)目名稱,選擇安裝位置,,選擇安裝框架版本;創(chuàng)建。

如何用C#編寫一個(gè)Windows服務(wù)程序

3.找到MyService.cs ,右擊‘查看代碼’

如何用C#編寫一個(gè)Windows服務(wù)程序

如何用C#編寫一個(gè)Windows服務(wù)程序

添加如下代碼:

public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }
        string filePath = @"D:\MyServiceLog.txt";
        protected override void OnStart(string[] args)
        {//服務(wù)啟動(dòng)時(shí),執(zhí)行該方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務(wù)啟動(dòng)!");
            }
        }
        protected override void OnStop()
        {//服務(wù)關(guān)閉時(shí),執(zhí)行該方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務(wù)停止!");
            }
        }
    }

4.雙擊MyService.cs,在出現(xiàn)的界面中右擊–>選擇“添加安裝程序”。

如何用C#編寫一個(gè)Windows服務(wù)程序

點(diǎn)擊后,會(huì)自動(dòng)生產(chǎn)連個(gè)控件,sericcelnstaller1 和sericeProcessInstaller1

如何用C#編寫一個(gè)Windows服務(wù)程序

5.分別設(shè)置兩個(gè)控件的屬性

右擊serviceInstaller1 點(diǎn)擊屬性

如何用C#編寫一個(gè)Windows服務(wù)程序

分別設(shè)置:服務(wù)安裝的描述,服務(wù)的名稱,啟動(dòng)的類型 。

如何用C#編寫一個(gè)Windows服務(wù)程序

在serviceProcessInstaller1 ,設(shè)置Account(服務(wù)屬性系統(tǒng)級別),設(shè)置“本地服務(wù)”

如何用C#編寫一個(gè)Windows服務(wù)程序

6.找到項(xiàng)目,右擊“重新生成”。

如何用C#編寫一個(gè)Windows服務(wù)程序

7.在同一個(gè)解決方案下,添加Windows From項(xiàng)目應(yīng)用窗體:

①點(diǎn)擊“添加”,新建項(xiàng)目,選擇Windows窗體應(yīng)用。要注意添加時(shí),選擇的路徑,是否在同一個(gè)解決方案目錄下。

如何用C#編寫一個(gè)Windows服務(wù)程序

如何用C#編寫一個(gè)Windows服務(wù)程序

如何用C#編寫一個(gè)Windows服務(wù)程序

8.找到Form設(shè)計(jì)窗體,添加控件如圖。控件工具箱在菜單欄–>視圖–>找到‘工具箱’。如圖所示

如何用C#編寫一個(gè)Windows服務(wù)程序

如何用C#編寫一個(gè)Windows服務(wù)程序

9.Form窗體中,單擊空白窗體,按F7進(jìn)入命令界面。添加如下代碼:

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";//MyWindowsService.exe 是項(xiàng)目名稱對應(yīng)的服務(wù)
        string serviceName = "DemoService"; //這里時(shí)服務(wù)名,是第五點(diǎn)中,設(shè)置的名稱,要對應(yīng)好

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                myProcess.StartInfo.FileName = "cmd.exe";//啟動(dòng)cmd命令
                myProcess.StartInfo.UseShellExecute = false;//是否使用系統(tǒng)外殼程序啟動(dòng)進(jìn)程
                myProcess.StartInfo.RedirectStandardInput = true;//是否從流中讀取
                myProcess.StartInfo.RedirectStandardOutput = true;//是否寫入流
                myProcess.StartInfo.RedirectStandardError = true;//是否將錯(cuò)誤信息寫入流
                myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中啟動(dòng)進(jìn)程
                myProcess.Start();//啟動(dòng)進(jìn)程
                //myProcess.StandardInput.WriteLine("shutdown -s -t 0");//執(zhí)行關(guān)機(jī)命令
                myProcess.StandardInput.WriteLine("shutdown -r -t 60");//執(zhí)行重啟計(jì)算機(jī)命令
            }
            catch (Exception) { }
        }

        //停止服務(wù)
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("無法停止服務(wù)!"+ex.ToString());
            }
        }

        //事件:安裝服務(wù)
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
                this.InstallService(serviceFilePath);
                MessageBox.Show("安裝服務(wù)完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           
        }
        /// <summary>
        ///事件:卸載服務(wù)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                    this.UninstallService(serviceFilePath);
                    MessageBox.Show("卸載服務(wù)完成");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }

        //事件:啟動(dòng)服務(wù)
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
                MessageBox.Show("啟動(dòng)服務(wù)完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }


        //判斷服務(wù)是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //安裝服務(wù)
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //卸載服務(wù)
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }

        //啟動(dòng)服務(wù)
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //停止服務(wù)
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
    }

10.為了后續(xù)調(diào)試服務(wù)及安裝卸載服務(wù)的需要,將已生成的MyWindowsService.exe引用到本W(wǎng)indows窗體,如下圖所示:

如何用C#編寫一個(gè)Windows服務(wù)程序

如何用C#編寫一個(gè)Windows服務(wù)程序

11.由于需要安裝服務(wù),故需要使用UAC中Administrator的權(quán)限,鼠標(biāo)右擊項(xiàng)目“WindowsServiceClient”,在彈出的上下文菜單中選擇“添加”->“新建項(xiàng)”,在彈出的選擇窗體中選擇“應(yīng)用程序清單文件”并單擊確定,如下圖所示:

如何用C#編寫一個(gè)Windows服務(wù)程序

打開該文件,并將改為,如下圖所示:

如何用C#編寫一個(gè)Windows服務(wù)程序

12.IDE啟動(dòng)后,將會(huì)彈出如下所示的窗體(有的系統(tǒng)因UAC配置有可能不顯示),需要用管理員權(quán)限打開

如何用C#編寫一個(gè)Windows服務(wù)程序

13.效果圖

單擊安裝服務(wù)

如何用C#編寫一個(gè)Windows服務(wù)程序

找到服務(wù),可以查看到。

如何用C#編寫一個(gè)Windows服務(wù)程序

卸載服務(wù)

如何用C#編寫一個(gè)Windows服務(wù)程序

服務(wù)卸載成功,找不到服務(wù)。

如何用C#編寫一個(gè)Windows服務(wù)程序

以上就是“如何用C#編寫一個(gè)Windows服務(wù)程序”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI