代码如下(很短):
// 服务程序和窗口程序有些类似,ServiceMain和WinMain有些相似,ControlHandler和窗口过程有些相似,\
//但是服务程序仍然有WinMain或者Main函数(用于控制台)
#include <windows.h>
#include <Winsvc.h>
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
HEVENT hevent; //编译的时候提示这里有错误,我不知道为什么错了,不解啊
void WINAPI ControlHandler(DWORD ControlCode)
{
switch(ControlCode)
{
case SERVICE_ACCEPT_STOP:
ServiceStatus.dwCurrentState=SERVICE_STOP_PENDING;
SetServiceStatus(hStatus,&ServiceStatus);
SetEvent(hevent);
break;
case 0xa0:
Beep(1000,1000);
break;
default:
break;
}
}
void WINAPI ServiceMain(int argc, LPTSTR *lpszArgv) //ServiceMain函数结束就代表服务终止
{
hStatus=RegisterServiceCtrlHandler("beep",(LPHANDLER_FUNCTION)ControlHandler);
ServiceStatus.dwServiceType=SERVICE_WIN32_OWN_PROCESS;
ServiceStatus.dwCurrentState=SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP+0xa0;
ServiceStatus.dwWin32ExitCode=NO_ERROR;
SetServiceStatus(hStatus,&ServiceStatus);
//------------在这里加入初始化代码---------------------------------
ServiceStatus.dwCurrentState=SERVICE_RUNNING;
SetServiceStatus(hStatus,&ServiceStatus);
hevent=CreateEvent(NULL,TRUE,FALSE,NULL); //事件对象初始状态被设置为复位
WaitForSingleObject(hevent,INFINITE);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = "beep";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
StartServiceCtrlDispatcher(ServiceTable); //注册服务主程序ServiceMain
return 0;
}
这是学习服务程序的时候写的最简单的服务程序,编译的时候提示有以下错误:
C:\Documents and Settings\Owner\桌面\服务程序模板\ServiceTemplate.cpp(7) : error C2146: syntax error : missing ';' before identifier 'hevent'
C:\Documents and Settings\Owner\桌面\服务程序模板\ServiceTemplate.cpp(7) : error C2501: 'HEVENT' : missing storage-class or type specifiers
C:\Documents and Settings\Owner\桌面\服务程序模板\ServiceTemplate.cpp(7) : fatal error C1004: unexpected end of file found
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课