2017/03/19

[C/Cpp] Start/Stop a Windows Service

一般要手動啟動或是停止Windows的某個Service,都是啟動工作管理員,再到服務(Service)清單中去選擇某個Service。

為了方便一點,有找到可以在程式中可以自動監控Service的狀態,甚至可以自動控制Service的方法:




  1. #include <Windows.h>
  2. int main()
  3. {
  4. LPCWSTR ServiceName = L"YourServiceName";
  5. SC_HANDLE serviceDbHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  6. SC_HANDLE serviceHandle = OpenService(serviceDbHandle, ServiceName, SC_MANAGER_ALL_ACCESS);
  7.  
  8. SERVICE_STATUS_PROCESS status;
  9. DWORD bytesNeeded;
  10.  
  11. // detect service
  12. QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded);
  13.  
  14. // control service
  15. if (status.dwCurrentState == SERVICE_STOPPED) {
  16. cout << "Service stop!" << std::endl;
  17. BOOL b = StartService(serviceHandle, NULL, NULL);
  18. if (b) {
  19. cout << "Service start" << endl;
  20. }
  21. else{
  22. cout << "Service start fail" << endl;
  23. }
  24. }
  25. CloseServiceHandle(serviceHandle); CloseServiceHandle(serviceDbHandle);
  26. }

如果是要把Service停止的話,就把control service那段改成:
  1. if (status.dwCurrentState == SERVICE_RUNNING) {
  2. cout << "Service is running!" << std::endl;
  3. BOOL b = ControlService(serviceHandle, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &status);
  4. if (b) {
  5. cout << "Service stop" << std::endl;
  6. }
  7. else{
  8. cout << "Service stop" << std::endl;
  9. }
  10. }

最後記得!產生的執行檔必須要"以系統管理員身分執行",這樣才有足夠權限可以控制Windows的Service。

沒有留言:

張貼留言