I want to catch a Windows logoff event so that I can do some cleanup. My WindowProc looks like this:
switch (uMsg){
case WM_ENDSESSION:
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// other messages
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
and the message loop in WinMain looks like this:
for(;;){
bool bTerminate = false;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
if(msg.message == WM_QUIT){
bTerminate = true;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if(bTerminate){
break;
}
// do other stuff
Sleep(10);
}
FILE * fout;
fopen_s(&fout, "C:\\success.txt", "w"); // simulating cleanup actions
fclose(fout);
ExitProcess(0);
The intended mechanism is that WindowProc does PostQuitMessage, causing the main message loop to receive WM_QUIT, breaking the loop and sending the program to cleanup. When I exit the program (thus sending WM_DESTROY) the program creates success.txt, but when the program is running and I log off (sending WM_ENDSESSION), it does not.
I have looked at WM_QUERYENDSESSION as well, but MSDN says "Each application should return TRUE or FALSE immediately upon receiving this message, and defer any cleanup operations until it receives the WM_ENDSESSION message."
WM_ENDSESSIONprocessing doesn't actually give your application a chance to exit the message loop. You should assume the system calls TerminateProcess after sending theWM_ENDSESSIONmessage.Therefore, any clean-up your application needs to perform should be done before returning from the window procedure.