1. 新建console程序
2. 将如下代码拷到程序中
#include <windows.h>
#include <stdio.h>
class CWinService
{
public:
static void RunService(LPCTSTR lpszSeriveName);
private:
enum { SLEEP_TIME = 5000};
static SERVICE_STATUS ServiceStatus;
static SERVICE_STATUS_HANDLE hStatus;
static TCHAR serviceName[MAX_PATH];
private:
static void ServiceMain(int argc, char** argv);
static void ControlHandler(DWORD request);
static int InitService();
};
SERVICE_STATUS CWinService::ServiceStatus;
SERVICE_STATUS_HANDLE CWinService::hStatus;
TCHAR CWinService::serviceName[MAX_PATH];
void CWinService::RunService(LPCTSTR lpszSeriveName)
{
_tcscpy(serviceName, lpszSeriveName);
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = new TCHAR[MAX_PATH];
_tcscpy(ServiceTable[0].lpServiceName, lpszSeriveName);
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)CWinService::ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// Start the control dispatcher thread for our service
StartServiceCtrlDispatcher(ServiceTable);
delete []ServiceTable[0].lpServiceName;
}
int CWinService::InitService()
{
OutputDebugString(L"Monitoring started.");
return 0;
}
// Control Handler
void CWinService::ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
OutputDebugString(L"Monitoring stopped.");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
OutputDebugString(L"Monitoring stopped.");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
// Report current status
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
void CWinService::ServiceMain(int argc, char** argv)
{
int error;
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(serviceName,(LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
return;
}
// Initialize Service
error = InitService();
if (error)
{
// 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);
MEMORYSTATUS memory;
// The worker loop of a service
while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
Sleep(SLEEP_TIME );
}
return;
}
void main(int argc, char* argv[])
{
CWinService::RunService(L"AcebyteAutoCare");
}
注册服务
sc create xxxx binpath= "c:\xxxx.exe" displayname= "xxxxx" start= auto