Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: cleanup actions in response to Windows logoff

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."

like image 290
user1763950 Avatar asked Dec 05 '25 18:12

user1763950


1 Answers

WM_ENDSESSION processing doesn't actually give your application a chance to exit the message loop. You should assume the system calls TerminateProcess after sending the WM_ENDSESSION message.

Therefore, any clean-up your application needs to perform should be done before returning from the window procedure.

like image 185
Neil Avatar answered Dec 07 '25 06:12

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!