2017/03/19

[C/Cpp] Start/Stop a Windows Service

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

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




#include <Windows.h>
int main()
{
 LPCWSTR ServiceName = L"YourServiceName";
 SC_HANDLE serviceDbHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
 SC_HANDLE serviceHandle = OpenService(serviceDbHandle, ServiceName, SC_MANAGER_ALL_ACCESS);

 SERVICE_STATUS_PROCESS status;
 DWORD bytesNeeded;

 // detect service
 QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded);

 // control service
 if (status.dwCurrentState == SERVICE_STOPPED) {
  cout << "Service stop!" << std::endl;
  BOOL b = StartService(serviceHandle, NULL, NULL);
  if (b) {
   cout << "Service start" << endl;
  }
  else{
   cout << "Service start fail" << endl;
  }
 }
 CloseServiceHandle(serviceHandle); CloseServiceHandle(serviceDbHandle);
}

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

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

沒有留言:

張貼留言