第三步,添加注册表:
当系统启动的时候,Services.exe会遍历HKEY_LOCAL_MACHINE\Services注册表位置下子键,每个子键代表一个服务,Services.exe按照对应键值初始化服务,并且按照键值指定的顺序。
HKEY_LOCAL_MACHINE\Services\<Service Name>下的键值的说明:
Context : REG_DWORD类型 Specifies the initial value that is passed into the initialization routine.
Description : REG_SZ Description of display service.
DisplayName : REG_SZ Display service name.
Dll : REG_SZ Dynamic-link library (DLL) file to be loaded.
Flags : REG_DWORD Specifies a set of flags used to modify the behavior of the ActivateService function. The following list shows the valid flags:
DEVFLAGS_NONE (0x00000000): No flags defined.
DEVLFAGS_UNLOAD (0x00000001): Unload service after call to xxx_Init (Services.exe) returns.
DEVFLAGS_LOADLIBRARY (0x00000002): Use the LoadLibrary function to load the service DLL.
DEVFLAGS_NOLOAD (0x00000004): Do not load the service.
DEVFLAGS_TRUSTEDCALLERONLY (0x00010000) : This service only can be called by a privileged process.
DEVFLAGS_NOUNLOAD(0x00000020): Do not allow the service to be unloaded.
Index : REG_SZ Service index.
Keep : REG_DWORD If Keep = 0, the DLL will be unloaded immediately after initialization.
Order : REG_DWORD Order in which Services.exe will load each service. The service with the lowest order is loaded first.
Prefix : REG_SZ Prefix of the DLL.(3个英文字符。为什么?看看文档里介绍的Service.exe在调用上面这些函数时做的操作。)
一个具体例子:
[HKEY_LOCAL_MACHINE\Services\MySevice]
"Description"="MySevice"
"DisplayName"="MySevice"
"Prefix"="OBX"
"Dll"="mysevice.dll"
"Index"=dword:0
"Keep"=dword:1
"Order"=dword:9
第四步,代码签名,不签名的服务DLL不会被加载的,这也服务运行失败的常见原因。
签名工具在此。
SDK自带的一些证书,在模拟器上实验是可以的:

2009.6.22更新:虽然.Net CF没有提供任何接口创建Windows Services,但是使用托管代码开发朋友可以参考这篇文章使用C#等语言创建服务。