Windows服务程序的编写要点
- 填充 DispatchTable
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{(LPTSTR)"Serveric Name",(LPSERVICE_MAIN_FUNCTION) Service},
{NULL, NULL}
};
- 调用StartServiceCtrlDispatcher(DispatchTable);
- 启动Service(),以下均在Service()函数中完成
- 生成ServiceStatusHandle
ServiceStatusHandle = RegisterServiceCtrlHandler(
LPCTSTR("Service Name"),
(LPHANDLER_FUNCTION)ServiceCtrlHandler);
- 设置服务状态
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = NULL;
ServiceStatus.dwServiceSpecificExitCode = NULL;
ServiceStatus.dwCheckPoint = NULL;
ServiceStatus.dwWaitHint = NULL;
SetServiceStatus (ServiceStatusHandle, &ServiceStatus);
- 从ServiceCtrlHandler()中发出结束服务的信号
if(Opcode==SERVICE_CONTROL_STOP || Opcode==SERVICE_CONTROL_SHUTDOWN)
{
ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus (ServiceStatusHandle,&ServiceStatus);
bRunning=false;
}
- 在Service() 中终止服务
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (ServiceStatusHandle,&ServiceStatus);