Saturday, May 9, 2009

How to receive OS notifications about windows shutdown/logoff

To create a process which must detect windows shutdown or log-off actions to perform necessary clean-up operations you can use many features.

One of them is to create Windows Service.
Another way is to subscribe to the system events notifications.

WinAPI provides a SetConsoleCtrlHandler function which able to add a callback for the calling process.

#include <windows.h>


HANDLE hEvent;


BOOL WINAPI ShutDownHandler(DWORD dwCtrlType)

{

switch( dwCtrlType )

{

case CTRL_SHUTDOWN_EVENT:


case CTRL_LOGOFF_EVENT:


case CTRL_CLOSE_EVENT:

SetEvent(hEvent);

return TRUE;


default:

return FALSE;

}

}

void main()

{

hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

SetConsoleCtrlHandler(ShutDownHandler, true);

// your implementation

WaitForSingleObject(hEvent,INFINITE);

// your clean-up


CloseHandle (hEvent);

}

0 comments:

Post a Comment