ServiceController.ExecuteCommand爲何爲調用失敗?

問題:假設在地有一個自定義的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的時候,可以這麼做:
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章