windows服务控制程序
#include <iostream>
#include <Windows.h>
BOOL DeleteSampleService(SC_HANDLE scSCManager, LPCWSTR szNameOfService);
DWORD StopService(SC_HANDLE scSCManager, LPCWSTR ServiceName, BOOL fStopDependencies, DWORD dwTimeout);
BOOL CreateSampleService(SC_HANDLE scSCManager, LPCWSTR szPath, LPCWSTR szServiceName) {
SC_HANDLE schService = CreateService(
scSCManager,
szServiceName,
TEXT("aaaaaaaa"),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
szPath,
NULL,
NULL,
NULL,
NULL,
NULL
);
if (schService == NULL) {
printf("'createService failed %d \n", GetLastError());
if (GetLastError() == ERROR_SERVICE_EXISTS) {
StopService(scSCManager, szServiceName, TRUE, 100);
DeleteSampleService(scSCManager, szServiceName);
CreateSampleService(scSCManager, szPath, szServiceName);
}
else {
return FALSE;
}
}
else {
printf("createService succeed\n");
}
CloseServiceHandle(schService);
return TRUE;
}
BOOL DeleteSampleService(SC_HANDLE scSCManager, LPCWSTR szNameOfService) {
SC_HANDLE schService = OpenService(scSCManager, szNameOfService, DELETE);
if (schService == NULL) {
printf("'DeleteService failed %d \n", GetLastError());
return FALSE;
}
else {
if (!DeleteService(schService)) {
printf("'DeleteService succeed \n");
}
}
CloseServiceHandle(schService);
return TRUE;
}
BOOL StartSampleService(SC_HANDLE scSCManager, LPCWSTR szNameofService) {
SC_HANDLE schService;
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded;
schService = OpenService(scSCManager, szNameofService, SERVICE_ALL_ACCESS);
if (schService == NULL) {
printf("OpenService failed %d \n", GetLastError);
return FALSE;
}
if (!StartService(
schService,
0,
NULL
)) {
printf("Service Start error(%u) \n", GetLastError());
return FALSE;
}
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssStatus,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded
)) {
printf("QueryServiceStatus failed %d\n", GetLastError());
return FALSE;
}
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
while (ssStatus.dwCurrentState == SERVICE_START_PENDING) {
dwWaitTime = ssStatus.dwWaitHint / 10;
if (dwWaitTime !=1000) {
dwWaitTime = 1000;
}
Sleep(dwWaitTime);
if (!