//定义全局函数变量 void Init(); BOOL IsInstalled(); BOOL Install(); BOOL Uninstall(); void LogEvent(LPCTSTR pszFormat, ...); void WINAPI ServiceMain(); void WINAPI ServiceStrl(DWORD dwOpcode); TCHAR szServiceName[] = _T("ServiceTest"); BOOL bInstall; SERVICE_STATUS_HANDLE hServiceStatus; SERVICE_STATUS status; DWORD dwThreadID; |
hServiceStatus = NULL; status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwCurrentState = SERVICE_STOPPED; tatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; status.dwWin32ExitCode = 0; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 0; status.dwWaitHint = 0; |
BOOL Install(); { //这里列出主要的两个函数,其它的可以在代码里找。 //打开服务控制管理器 OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); //创建服务 SC_HANDLE hService = ::CreateService( hSCM, szServiceName, szServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szFilePath, NULL, NULL, _T(""), NULL, NULL); ::CloseServiceHandle(hService); ::CloseServiceHandle(hSCM); } BOOL Uninstall(); { //这里列出主要的两个函数,其它的可以在代码里找。 //打开服务控制管理器 OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); //打开服务 OpenService(hSCM, szServiceName, SERVICE_STOP | DELETE); //停止服务 ControlService(hService, SERVICE_CONTROL_STOP, &status); //删除服务 DeleteService(hService); … } |
五、添加服务主线程函数和控制函数
这里调用RegisterServiceCtrlHandler来注册服务的控制函数,这里要设置status.dwControlsAccepted为SERVICE_ACCEPT_STOP,否则你不能控制这个服务的状态。
void WINAPI ServiceMain() { // Register the control request handler status.dwCurrentState = SERVICE_START_PENDING; status.dwControlsAccepted = SERVICE_ACCEPT_STOP;//这个要使用,否则你不能控制 //注册服务控制 hServiceStatus = RegisterServiceCtrlHandler(szServiceName, ServiceStrl); if (hServiceStatus == NULL) { LogEvent(_T("Handler not installed")); return; } SetServiceStatus(hServiceStatus, &status); status.dwWin32ExitCode = S_OK; status.dwCheckPoint = 0; status.dwWaitHint = 0; status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(hServiceStatus, &status); //模拟服务的运行,10后自动退出。应用时将主要任务放于此即可 int i = 0; while (i < 10) { Sleep(1000); i++; } // status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(hServiceStatus, &status); LogEvent(_T("Service stopped")); } |
void WINAPI ServiceMain() { … //如上,这里主要是说明这就是程序的执行体 //模拟服务的运行,10后自动退出。应用时将主要任务放于此即可 int i = 0; while (i < 10) { Sleep(1000); i++; } … } |
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { Init(); dwThreadID = ::GetCurrentThreadId(); SERVICE_TABLE_ENTRY st[] = { { szServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain }, { NULL, NULL } }; if (stricmp(lpCmdLine, "/install") == 0) { Install(); } else if (stricmp(lpCmdLine, "/uninstall") == 0) { Uninstall(); } else { if (!::StartServiceCtrlDispatcher(st)) { LogEvent(_T("Register Service Main Function Error!")); } } return 0; } |