问题:假设在地有一个自定义的Service,我们想通过另外一个程序来给它发送一个自定义的命令(比如说),怎么办?做法很简单:
可是,当调用时却抛出异常,
中文版:
[System.InvalidOperationException] = {"无法控制计算机“LL-PC”上的 MyService服务。"}
{System.ComponentModel.Win32Exception: 拒绝访问。}
英文版:
Cannot control <service name> service on computer '.'
Access denied.
Why?
刚刚开始以为是权限的问题,结果朝着这个方向调查了两小时,未果。最后终于知道为什么了,ServiceController.ExecuteCommand(int command)这个函数的参数调用错误。该参数的取值范围必须是128~255。悲剧了,万恶的MSDN居然没有解释。其实,MSDN也是给出了解释的,只不过并没有在.NET类库中做解释,我用.NET Reflector 7.0 反编译了一下 System.ServiceProcess.dll ,发现该函数最终调用的函数是 ControlService 这个API,而在这个API中,它做了一段解释。
This value can also be a user-defined control code, as described in the following table.
Control code: Range 128 to 255
Meaning: The service defines the action associated with the control code. The hService handle must have the SERVICE_USER_DEFINED_CONTROL access right.
因此,我们可以在定义Command的时候,可以这么做: