this.serviceInstaller1});} 注意将服务安装设置为:手动安装 服务安装卸载脚本 Install.

时间:2022-03-20 03:52:05

学然后知不敷 教然后知困。

没做过windows service开发时,觉得很难,无从下手。再网看了些例子,加上本身的理解,,写下开发法式。

开发法式

新建windows service

this.serviceInstaller1});} 注意将服务安装设置为:手动安装 服务安装卸载脚本 Install.

添加处事,发表后将再本身的电脑的 处事打点 检察到

this.serviceInstaller1});} 注意将服务安装设置为:手动安装 服务安装卸载脚本 Install.

partial class MyService : ServiceBase { Timer timer1; public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: Add code here to start your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Start."); } timer1 = new Timer(); timer1.Interval = 2000; timer1.Elapsed += (sender, e) => { using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Countue..."); } }; timer1.Start(); } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Stop."); } } }

添加处事安置措施(这是vs给供给的便利操纵),可以发表多个处事。

this.serviceInstaller1});} 注意将服务安装设置为:手动安装 服务安装卸载脚本 Install.

右击,点击Add Installer,自动生成类ProjectInstaller。大家可以看下vs自动生成的类ProjectInstaller.Designer.cs文件

private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); //设置处事安置信息 this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; //要安置的处事(保证与你的处事名一致,可添加多个) this.serviceInstaller1.ServiceName = "MyService"; //处事插手 this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); }

注意将处事安置设置为:手动安置

处事安置卸载脚本
Install.bat 文件:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "%~dp0%WindowsServiceTest.exe" pause

Uninstall.bat文件:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "%~dp0%WindowsServiceTest.exe" pause