I have written Windows Service in VC++ to mount Drives on System restart. Now when i restart the system, on system shutdown i want to fire my service stop event which is not getting fired.
I have set Windows service properties as automatic but it does not work. When i manually click on stop button stop event get fired.
Any help is apprecaited. My code looks like :
void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
switch(O开发者_开发知识库pcode)
{
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;
}
This is relatively straight forward. Either handle the SERVICE_CONTROL_SHUTDOWN in your current callback handler function by adding another case to the switch statement. Probably something like:
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:
Instead of registering the callback function with RegisterServiceCtrlHandler use RegisterServiceCtrlHandlerEx. This new callback method is preferred. Your callback function's signature needs to match HandlerEx, see MSDN for more info.
DWORD WINAPI HandlerEx(
__in DWORD dwControl,
__in DWORD dwEventType,
__in LPVOID lpEventData,
__in LPVOID lpContext
);
Add another case to your switch statement, either SERVICE_CONTROL_PRESHUTDOWN (not available on XP/Server 2003) or SERVICE_CONTROL_SHUTDOWN, read the warnings about handling these notifications in the HandlerEx documentation referenced above.
精彩评论