我已经用VC ++编写了Windows Service来在系统重启时挂载驱动器。 现在,当我重新启动系统时,在系统关闭时,我想触发我的服务停止事件,该事件未被触发。
我已将Windows服务属性设置为自动,但不起作用。 当我手动点击停止按钮时,停止事件被触发。
任何帮助都是适用的。 我的代码如下:
void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
switch(Opcode)
{
case SERVICE_CONTROL_PAUSE:
m_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_STOP:
m_ServiceStatus.dwWin32ExitCode = 0;
m_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
m_ServiceStatus.dwCheckPoint = 0;
m_ServiceStatus.dwWaitHint = 0;
Disconnect() ;// This method i want to get called on system shot down automatically.
SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus);
bRunning=false;
break;
case SERVICE_CONTROL_INTERROGATE:
break;
}
return;
}
答案 0 :(得分:2)
这是相对简单的。 通过向switch语句添加另一个case来处理当前回调处理函数中的SERVICE_CONTROL_SHUTDOWN。可能类似于:
void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
switch(Opcode)
{
case SERVICE_CONTROL_PAUSE:
m_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_STOP:
m_ServiceStatus.dwWin32ExitCode = 0;
m_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
m_ServiceStatus.dwCheckPoint = 0;
m_ServiceStatus.dwWaitHint = 0;
Disconnect() ;// This method i want to get called on system shot down automatically.
SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus);
bRunning=false;
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
Disconnect();
break;
}
return;
}
OR:
使用RegisterServiceCtrlHandlerEx而不是使用RegisterServiceCtrlHandler注册回调函数。这种新的回调方法是首选。您的回调函数的签名需要与HandlerEx, see MSDN for more info匹配。
DWORD WINAPI HandlerEx(
__in DWORD dwControl,
__in DWORD dwEventType,
__in LPVOID lpEventData,
__in LPVOID lpContext
);
在switch语句中添加另一个案例,即SERVICE_CONTROL_PRESHUTDOWN(在XP / Server 2003上不可用)或SERVICE_CONTROL_SHUTDOWN,在上面引用的HandlerEx文档中阅读有关处理这些通知的警告。