SERVICE_STATUS ServiceStatus; SERVICE_STATUS_HANDLE hStatus;
int main() // 初始化服务列表,把当前服务加入到服务控件管理器中 { SERVICE_TABLE_ENTRY ServiceTable[2]; ServiceTable[0].lpServiceName = "PrinterServer"; ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
// 哨兵 ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceProc = NULL; // Start the control dispatcher thread for our service 连接到服务控制管理器 StartServiceCtrlDispatcher(ServiceTable); return 0; }
void WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) //ServiceMain() { ServiceStatus.dwServiceType = SERVICE_WIN32; ServiceStatus.dwCurrentState = SERVICE_START_PENDING; ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwServiceSpecificExitCode = 0; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler( "PrinterServer", (LPHANDLER_FUNCTION)ControlHandler); if (hStatus == (SERVICE_STATUS_HANDLE)0) { // Registering Control Handler failed return ; } // Initialize Service int error = InitService(); if (error == -1) { // Initialization failed ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = -1; SetServiceStatus(hStatus, &ServiceStatus); return; } // We report the running status to SCM. ServiceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus (hStatus, &ServiceStatus);
// 以下为主处理程序
}
// Control Handler 用于响应服务控件器的各个事件,此件处理了"stop","shut" void ControlHandler(DWORD request) { switch(request) { case SERVICE_CONTROL_STOP: OutputDebugString("Monitoring stopped."); WriteToLog("Monitoring stopped.");
ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus); return;
case SERVICE_CONTROL_SHUTDOWN: OutputDebugString("Monitoring stopped."); WriteToLog("Monitoring stopped.");
ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus); return; default: break; } // Report current status SetServiceStatus (hStatus, &ServiceStatus); return; }
// 以下为服务安装脚本
[Version] Signature="$WINDOWS NT$" [DefaultInstall.Services] AddService=PrinterServer,,My_Printer_Server [My_Printer_Server] DisplayName= Printer Server Description=提供对打印数据的截取功能。 // 如果想设置为“允许服务与桌面交互”类型,则把serviceType设置为110 ServiceType=0x10 StartType=2 ErrorControl=1 ServiceBinary=D:/PrinterServer.exe
// 以下为卸载服务脚本
[Version] Signature="$WINDOWS NT$" [DefaultInstall.Services] DelService=PrinterServer
如果启动服务失败,请先确认是否缺少以下四个动态库:
MFC71.dll
Msvcp71.dll
Msvcr71.dll
Msvcrt.dll