转载:
#define _WIN32_WINNT 0x502#define _CRT_SECURE_NO_WARNINGS#include#include #include #include #include #include #include static const char* const lpServiceName = "ProtectService";static SERVICE_STATUS_HANDLE hServiceStatus = NULL;static SERVICE_STATUS ServiceStatus = { 0};static char szCurDir[MAX_PATH+1] = { 0};static bool bRun = false;static HANDLE hProcess = NULL;static FILE* fLog = NULL;static std::ofstream ofs_log;bool InstallService();VOID WINAPI ServiceMain(DWORD dwArgc,LPTSTR *lpszArgv);VOID WINAPI HandlerFunc(DWORD dwControl);HANDLE RunAsLoggedUser(const char* lpPath,char* lpCmdLine);void WorkFunc();int main(int argc, char **argv){ GetModuleFileName(NULL,szCurDir,MAX_PATH); *strrchr(szCurDir,'\\') = '\0'; char szLogPath[MAX_PATH+1]; sprintf(szLogPath,"%s\\Service.log",szCurDir); fLog = fopen(szLogPath,"a+"); setvbuf(fLog,NULL,_IONBF,1024); ofs_log.open(szLogPath,std::ios::app); SERVICE_TABLE_ENTRY ServiceTable[2]; char szBuffer[30]; strcpy(szBuffer,lpServiceName); ServiceTable[0].lpServiceName = szBuffer; ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain; ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceProc = NULL; // 启动服务的控制分派机线程 if (!StartServiceCtrlDispatcher(ServiceTable)) { ofs_log<<"程序不是以服务方式启动"<