http://www.vckbase.com/index.php/wv/1193
//服务程序主函数。
//#include "stdafx.h"
#include "Windows.h"
#include "Tchar.h"
#include <stdio.h>
#define SZAPPNAME "serverSample" //服务程序名
#define SZSERVICENAME "serviceSample" //标识服务的内部名
//内部变量
bool bDebugServer=false;
SERVICE_STATUS ssStatus;
SERVICE_STATUS_HANDLE sshStatusHandle;
DWORD dwErr=0;
TCHAR szErr[256];
//下面的函数由程序实现
void WINAPI Service_Main(DWORD dwArgc, LPTSTR *lpszArgv);
void WINAPI Service_Ctrl(DWORD dwCtrlCode);
void installService();
void removeService();
void debugService(int argc,char** argv);
bool ReportStatusToSCMgr(DWORD dwCurrentState,DWORD dwWin32ExitCode,DWORD dwWaitHint);
void AddToMessageLog(LPTSTR lpszMsg);
int _tmain(int argc, _TCHAR* argv[])
{
SERVICE_TABLE_ENTRY dispatchTable[]=
{
{TEXT(SZSERVICENAME),(LPSERVICE_MAIN_FUNCTION)Service_Main},
{ NULL,NULL}
};
if((argc>1)&&(((char *)*argv[1]=='-')||((char *)argv[1]=="/")))
{
if(_stricmp("install",(char *)(argv[1]+1))==0)
{
installService();
}
else if(_stricmp("remove",(char *)(argv[1]+1))==0)
{
removeService();
}
else if(_stricmp("debug",(char *)(argv[1]+1))==0)
{
bDebugServer=true;
debugService(argc,(char **)argv);
}
else
{ //如果未能和上面的如何参数匹配,则可能是服务控制管理程序来启动该程序。立即调用
//StartServiceCtrlDispatcher 函数。
printf("%s - install to install the service \n",SZAPPNAME);
printf("%s - remove to remove the service \n",SZAPPNAME);
printf("%s - debug to debug the service \n",SZAPPNAME);
printf("\n StartServiceCtrlDispatcher being called.\n");
printf("This may take several seconds.Please wait.\n");
if(!StartServiceCtrlDispatcher(dispatchTable))
AddToMessageLog(TEXT("StartServiceCtrlDispatcher failed."));
else
AddToMessageLog(TEXT("StartServiceCtrlDispatcher OK."));
}
exit(0);
}
return 0;
}