.Net中用C#创建Windows Service,其实很简单,按照以下的步骤就可以做出一个简单的Windows Service

1.首先在创建工程的时候选择Windows Service,这样.Net会自动生成Windows Service的框架;

2.完成Windows Service的相应事件,主要是OnStartOnStop这两个事件,完成后大致代码如下:

如何用C#创建Windows Serviceusing System;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Collections;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.ComponentModel;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Data;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Diagnostics;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.ServiceProcess;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.IO;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Threading;
如何用C#创建Windows Service
如何用C#创建Windows Service
namespace WinSDemo
如何用C#创建Windows Service


注:为了使自己能更好的识别自己写的Windows Service,建议在InitializeComponent修改Service的名称。

 

3.为了使自己写的Service能加载到系统中去,光靠以上步骤是不够;接下来,向当前的工程添加Service Installer,在其中设置Service安装后的起始状态,代码如下:

如何用C#创建Windows Serviceusing System;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Collections;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.ComponentModel;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.Configuration.Install;
如何用C#创建Windows Service
如何用C#创建Windows Service
using System.ServiceProcess;
如何用C#创建Windows Service
如何用C#创建Windows Service 
如何用C#创建Windows Service
如何用C#创建Windows Service 
如何用C#创建Windows Service
如何用C#创建Windows Service
namespace WinSDemo
如何用C#创建Windows Service


4.完成以上的步骤,代码的部分就完成了,编译成可执行文件,再用.NetService安装工具就行了,即在Dos窗口中,键入“installutil yourService.exe”,这样执行就可以了,相反,如果想卸载Service的话,加一个参数就可以了,即“installutil /u yourService.exe”。注意有可能.Net的路径在环境变量中不存在,可能直接执行是不能成功的,希望先找到“installutil.exe”存在的目录,大致在“\WINDOWS\Microsoft.NET\Framework\v1.1.4322”目录下。

 

至于以后Service的部署,由于.Net写的程序,运行环境必须要安装.Net Framework,所以在其他机器安装自己写的Service时候,一定要先安装.Net运行环境。

相关文章: