#include <windows.h>
#include <cstdio>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;
class ServiceController {
private:
SC_HANDLE hSC;
public:
ServiceController(LPCTSTR MachineName = NULL, DWORD DesiredAccess = SC_MANAGER_ALL_ACCESS){
hSC = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(hSC == NULL){
SCHandleTest(GetLastError());
}
}
~ServiceController(){
CloseServiceHandle(hSC);
}
vector<ENUM_SERVICE_STATUS> EnumServices(DWORD SvcState = SERVICE_STATE_ALL){
vector<ENUM_SERVICE_STATUS> res;
DWORD svcRet, Bytes;
EnumServicesStatus(hSC, SERVICE_DRIVER | SERVICE_WIN32, SvcState, NULL, 0, &Bytes, &svcRet, 0);
ENUM_SERVICE_STATUS *pESS;
pESS = new ENUM_SERVICE_STATUS [Bytes / sizeof(ENUM_SERVICE_STATUS)];
EnumServicesStatus(hSC, SERVICE_DRIVER | SERVICE_WIN32, SvcState, pESS, Bytes, &Bytes, &svcRet, 0);
for(size_t i = 0; i < svcRet; i++){
res.push_back(pESS[i]
;
}
return res;
}
string FmtEnum(ENUM_SERVICE_STATUS ess){
string res = "";
char buff[1024];
sprintf(buff, "[%s] [%s] SvcType: %d; CurrState: %d; CtrlsAccepted: %d; WaitHint: %d ms",
ess.lpDisplayName, ess.lpServiceName,
ess.ServiceStatus.dwServiceType, ess.ServiceStatus.dwCurrentState,
ess.ServiceStatus.dwControlsAccepted, ess.ServiceStatus.dwWaitHint);
res.append(buff);
return res;
}
private:
void SCHandleTest(long retCode){
if(retCode == ERROR_ACCESS_DENIED){
throw "[ServiceController::OpenSCManager] Доступ запрещен";
} else if(retCode == ERROR_DATABASE_DOES_NOT_EXIST){
throw "[ServiceController::OpenSCManager] Запрошенная база данных не существует";
} else if(retCode == ERROR_INVALID_PARAMETER){
throw "[ServiceController::OpenSCManager] Неверно указаны параметры";
} else{
throw "[ServiceController::OpenSCManager] Неизвестная ошибка";
}
}
};
int main(){
ServiceController sc;
vector<ENUM_SERVICE_STATUS> res = sc.EnumServices();
for(size_t i = 0; i < res.size(); i++){
printf("%s\n", (sc.FmtEnum(res[i]
).c_str());
}
getch();
return 0;
}