使用C#創(chuàng)建Windows服務(wù)的實例代碼
本文介紹了使用C#創(chuàng)建Windows服務(wù)的實例代碼,分享給大家
一、開發(fā)環(huán)境
操作系統(tǒng):Windows 10 X64
開發(fā)環(huán)境:VS2015
編程語言:C#
.NET版本:.NET Framework 4.0
目標平臺:X86
二、創(chuàng)建Windows Service
1、新建一個Windows Service,并將項目名稱改為“MyWindowsService”,如下圖所示:
2、在解決方案資源管理器內(nèi)將Service1.cs改為MyService1.cs后并點擊“查看代碼”圖標按鈕進入代碼編輯器界面,如下圖所示:
3、在代碼編輯器內(nèi)如入以下代碼,如下所示:
using System; using System.ServiceProcess; using System.IO; namespace MyWindowsService { public partial class MyService : ServiceBase { public MyService() { InitializeComponent(); } string filePath = @"D:\MyServiceLog.txt"; protected override void OnStart(string[] args) { using (FileStream stream = new FileStream(filePath,FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服務(wù)啟動!"); } } protected override void OnStop() { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服務(wù)停止!"); } } } }
4、雙擊項目“MyWindowsService”進入“MyService”設(shè)計界面,在空白位置右擊鼠標彈出上下文菜單,選中“添加安裝程序”,如下圖所示:
5、此時軟件會生成兩個組件,分別為“serviceInstaller1”及“serviceProcessInstaller1”,如下圖所示:
6、點擊“serviceInstaller1”,在“屬性”窗體將ServiceName改為MyService,Description改為我的服務(wù),StartType保持為Manual,如下圖所示:
7、點擊“serviceProcessInstaller1”,在“屬性”窗體將Account改為LocalSystem(服務(wù)屬性系統(tǒng)級別),如下圖所示:
8、鼠標右鍵點擊項目“MyWindowsService”,在彈出的上下文菜單中選擇“生成”按鈕,如下圖所示:
9、至此,Windows服務(wù)已經(jīng)創(chuàng)建完畢。
三、創(chuàng)建安裝、啟動、停止、卸載服務(wù)的Windows窗體
1、在同一個解決方案里新建一個Windows Form項目,并命名為WindowsServiceClient,如下圖所示:
2、將該項目設(shè)置為啟動項目,并在窗體內(nèi)添加四個按鈕,分別為安裝服務(wù)、啟動服務(wù)、停止服務(wù)及卸載服務(wù),如下圖所示:
3、按下F7進入代碼編輯界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并輸入如下代碼:
using System; using System.Collections; using System.Windows.Forms; using System.ServiceProcess; using System.Configuration.Install; namespace WindowsServiceClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe"; string serviceName = "MyService"; //事件:安裝服務(wù) private void button1_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName); this.InstallService(serviceFilePath); } //事件:啟動服務(wù) private void button2_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName); } //事件:停止服務(wù) private void button4_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName); } //事件:卸載服務(wù) private void button3_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) { this.ServiceStop(serviceName); this.UninstallService(serviceFilePath); } } //判斷服務(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); } } //啟動服務(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(); } } } } }
4、為了后續(xù)調(diào)試服務(wù)及安裝卸載服務(wù)的需要,將已生成的MyWindowsService.exe引用到本W(wǎng)indows窗體,如下圖所示:
5、由于需要安裝服務(wù),故需要使用UAC中Administrator的權(quán)限,鼠標右擊項目“WindowsServiceClient”,在彈出的上下文菜單中選擇“添加”->“新建項”,在彈出的選擇窗體中選擇“應(yīng)用程序清單文件”并單擊確定,如下圖所示:
6、打開該文件,并將<requestedExecutionLevel level="asInvoker" uiAccess="false" />改為<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,如下圖所示:
7、IDE啟動后,將會彈出如下所示的窗體(有的系統(tǒng)因UAC配置有可能不顯示),需要用管理員權(quán)限打開:
8、重新打開后,在IDE運行WindowsServiceClient項目;
9、使用WIN+R的方式打開運行窗體,并在窗體內(nèi)輸入services.msc后打開服務(wù),如下圖所示:
10、點擊窗體內(nèi)的“安裝服務(wù)”按鈕,將會在服務(wù)中出現(xiàn)MyService,如下圖所示:
11、點擊“運行服務(wù)”按鈕,將啟動并運行服務(wù),如下所示:
12、點擊“停止服務(wù)”按鈕,將會停止運行服務(wù),如下圖所示:
13、點擊“卸載服務(wù)”按鈕,將會從服務(wù)中刪除MyService服務(wù)。
14、以上啟動及停止服務(wù)將會寫入D:\MyServiceLog.txt,內(nèi)容如下所示:
源代碼下載:MyWindowsService_jb51.rar
補充:如何調(diào)試服務(wù)
1、要調(diào)試服務(wù),其實很簡單,如需將服務(wù)附加進程到需要調(diào)試的項目里面即可,假如要調(diào)試剛才建的服務(wù),現(xiàn)在OnStop事件里設(shè)置斷點,如下所示:
2、啟動“WindowsServiceClient”項目,在“調(diào)試”菜單中選擇“附件到進程”(服務(wù)必須事先安裝),如下所示:
3、找到“MyWindowsService.exe”,點擊“附加”按鈕,如下圖所示:
4、點擊“停止服務(wù)”按鈕,程序?qū)谠O(shè)置斷點的地方中斷,如下圖所示:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。
欄 目:C#教程
本文標題:使用C#創(chuàng)建Windows服務(wù)的實例代碼
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5553.html
您可能感興趣的文章
- 01-10winform實現(xiàn)創(chuàng)建最前端窗體的方法
- 01-10C#實現(xiàn)自定義windows系統(tǒng)日志的方法
- 01-10C#使用Dispose模式實現(xiàn)手動對資源的釋放
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#動態(tài)創(chuàng)建button的方法
- 01-10C#使用windows服務(wù)開啟應(yīng)用程序的方法
- 01-10深入淺出23種設(shè)計模式
- 01-10winform創(chuàng)建不規(guī)則窗體的方法
- 01-10c# ArrayList的使用方法小總結(jié)
- 01-10C#動態(tài)創(chuàng)建Access數(shù)據(jù)庫及密碼的方法


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻 器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已
隨機閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 04-02jquery與jsp,用jquery
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實例總結(jié)
- 08-05織夢dedecms什么時候用欄目交叉功能?