问题
I have a problem with WM_ENDSESSION message. Namely I would like to exit from the main loop of the application (WindowProc) when the WM_ENDSESSION message is sending... So, I wrote something like that:
LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
//...
case WM_QUERYENDSESSION: return TRUE;
case WM_ENDSESSION:
if(wParam) PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
return 0;
}
..., but it doesn't work - application doesn't exit the main loop...
I read about WM_QUERYENDSESSION and WM_ENDSESSION on msdn, but I couldn't find any helpful information...
Any idea, where is the mistake?
回答1:
I don't think it's wrong to call PostQuitMessage in response to WM_QUERYENDSESSION.
WM_ENDSESSION is the end of the world. It's too late at that point to postpone work until a later time (calling PostQuitMessage). Do it now, or you'll never get a chance to do it. Also, consider what you are doing. As Raymond Chen once put it, "[cleaning up your app in response to WM_ENDSESSION is] like taking the time to steam-clean the rugs before you demolish the building. Wasted effort."
WM_QUERYENDSESSION grants your window a last-chance to interact with the user. You have decided on behalf of the user that your app will die and you want to gracefully exit, so this is your last opportunity to schedule it.
Updated
I don't know that will even work to PostQuitMessage in response to WM_QUERYENDSESSION. The MSDN docs state, "The WM_ENDSESSION message is sent to an application after the system processes the results of the WM_QUERYENDSESSION message."
Sent implies that the message pump doesn't get a crack at messages. Of course, even the doc authors often confuse sent and posted.
回答2:
You don't need any special handling. Just call DefWindowProc instead of handling these messages.
回答3:
I would put
switch(msg)
{
//...
case WM_ENDSESSION:
if(wParam) PostQuitMessage(0);
return 0;
//...
}
putting return 0;
should exit the program, if you are in the main()
function
来源:https://stackoverflow.com/questions/5734644/problem-with-wm-endsession-message