VC++ 创建Windows服务 (一)

2014-11-24 03:18:27 · 作者: · 浏览: 0

首先,附上Windows创建服务的源代码,这个很好用的,大家一般都是选择的这个使用。

[cpp]
#include"XXXX.h" //包含的头文件

//定义全局函数变量
void Init();
BOOL IsInstalled();
BOOL Install();
BOOL Uninstall();
void LogEvent(LPCTSTR pszFormat, ...);
void WINAPI ServiceMain();
void WINAPI ServiceStrl(DWORD dwOpcode);

TCHAR szServiceName[] = _T("WatchDog");
BOOL bInstall;
SERVICE_STATUS_HANDLE hServiceStatus;
SERVICE_STATUS status;
DWORD dwThreadID;

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;
}
//*********************************************************
//Functiopn: Init
//Description: 初始化
//Calls: main
// niying

hServiceStatus = NULL;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
status.dwWin32ExitCode = 0;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
}

//*********************************************************
//Functiopn: ServiceMain
//Description: 服务主函数,这在里进行控制对服务控制的注册
// niying