Windows Shutdown Messages/Events : WM_QUERYENDSESSION, WM_ENDSESSION

The WM_QUERYENDSESSION message is sent when the user chooses to end the session or when an application calls one of the system shutdown functions. If any application returns zero, the session is not ended. The system stops sending WM_QUERYENDSESSION messages as soon as one application returns zero.

After processing this message, the system sends the WM_ENDSESSION message with the wParam parameter set to the results of the WM_QUERYENDSESSION message.
A window receives this message through its WindowProc function.

How can I prevent my application from closing when I logoff?

When a user logs off from the console, all running applications are notified of the logoff event via the WM_QUERYENDSESSION and WM_ENDSESSIONWindows messages.

By default, Windows will exit your application in response to WM_ENDSESSION events so you must change your code to override that behavior.

Here is a sample in MFC/C++:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_ENDSESSION()
END_MESSAGE_MAP()

...

void CMainFrame::OnEndSession(BOOL bEnding)
{
// Figure out if logging off
BOOL bIsLoggingOff = FALSE;
{
const MSG* pMsg = GetCurrentMessage();
if ((pMsg->lParam & ENDSESSION_LOGOFF) != 0)
bIsLoggingOff = TRUE;
}

if (bIsLoggingOff) {
// Avoid the default behavior, which may close our application
TRACE("Ignoring logoff.\n")
return;
}

// Not logging off so proceed with the regular/default
CFrameWnd::OnEndSession(bEnding);
}

Reference:

Win32 API for ShutDown:- http://www.codersource.net/mfc_shutdown_timer.html

http://msdn.microsoft.com/en-us/library/aa376890(VS.85).aspx