I was wondering what the difference between the WM_QUIT, WM_CLOSE, and WM_DESTROY messages in a windows program, essentially: when are they sent, and do they have any automatic effects besides what's defined by the program?
views:
120answers:
3At first let's discuss WM_QUIT - the difference from another messages that this is not associated with window. It is used by application. For example this can be handled by non-visible standalone OLE server (.exe, but not in-proc as .dll)
WM_CLOSE - per msdn: "An application can prompt the user for confirmation, prior to destroying a window" - it is used as notification about intention to close (you can reject this intention).
WM_DESTROY - is a fact that window is closing and all resources must(!) be deallocated.
They are totally different.
WM_CLOSE
is sent to the window when "X" is pressed or "Close" is chosen from window menu. If you catch this message this is your call how to treat it - ignore it or really close the window. By default, WM_CLOSE
passed to DefWindowProc
causes window to be destroyed. When the window is being destroyed WM_DESTROY
message is sent. In this stage, in opposition toWM_CLOSE
, you cannot stop the process, you can only make a necessary cleanup. But remember that when you catch WM_DESTROY
all child windows are already destroyed. WM_NCDESTROY
is send just before destroying child windows.
WM_QUIT
message is not related to any window (the hwnd
got from GetMessage
is NULL and no window procedure is called). This message indicates that the message loop should be stopped and application should be closed. When GetMessage
reads WM_QUIT
it returns 0 to indicate that. Take a look at typical message loop snippet - the loop is continued while GetMessage
returns non-zero. WM_QUIT
can be sent by PostQuitMessage
function. This function is usually called when main window receives WM_DESTROY
(see typical window procedure snippet).
First of all, the WM_CLOSE and WM_DESTROY messages are are associated with particular windows whereas the WM_QUIT message is applicable to the whole application (well thread) and the message is never received through a window procedure (WndProc routine) but only through the GetMessage or PeekMessage functions.
In your WndProc routine the DefWindowProc function takes care of the default behavoir of these messages. The WM_CLOSE messages requests that the application should close and the default behavoir for this is to call the DestroyWindow function. Its when this DestroyWindow function is called that the WM_DESTROY message is sent. Notice that the WM_CLOSE is only a message requesting that you close (like WM_QUIT) - you don't actually have to exit/quit. But the WM_DESTROY message tells you that your window IS being closed and destroyed so you must cleanup any resources, handles etc.