C++: cleanup actions in response to Windows logoff

落花浮王杯 提交于 2019-12-07 15:44:29

问题


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


回答1:


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.




回答2:


In Windows UI applications, you can use: LRESULT CMainDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{ if(message == WM_ENDSESSION) { if(lParam == ENDSESSION_LOGOFF) { /*Handle event*/ } } return CDialogEx::WindowProc(message, wParam, lParam); }
You can get more help from this msdn link.



来源:https://stackoverflow.com/questions/13003165/c-cleanup-actions-in-response-to-windows-logoff

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!