I'm a bit confused currently: Are WM_CLOSE and ::CloseWindow
in any way "related" or are for completely different things?
The docs for Closing Windows don't mention the API function CloseWindow
at all. Should CloseWindow
be really called "MinimizeWindow" or what am I missing?
CloseWindow
and WM_CLOSE
are completely unrelated. The CloseWindow
function is badly named. Its inverse function, OpenWindow
is similarly badly named given that it restores windows.
I suspect these names dates back a very long way indeed, probably to Windows version 1 or 2. I'm speculating that what we now call minimize and restore were, back then, called close and open.
The usual way to minimize or restore a window is to call ShowWindow
passing SW_MINIMIZE
or SW_RESTORE
.
I suggest that you forget all about CloseWindow
and OpenWindow
.
CloseWindow
is an unusually poorly named winapi function. It doesn't actually close a window, it just minimizes it. What you possibly meant was DestroyWindow()
.
WM_CLOSE
is normally a message that's generated by default window procedure, in response to the user pressing Alt+F4 or clicking the window's close button. The underlying message is WM_SYSCOMMAND
, SC_CLOSE
. It can be generated in code as well, like a Window + Close menu item.
You can listen for WM_CLOSE
in your window procedure or the MFC message map. The user will expect the window to be closed. So you normally call DestroyWindow()
. You don't have to, you might display a message box for example and ask the user if data should be saved. And if he clicks No then you don't call DestroyWindow()
.
I would say ignore CloseWindow and OpenWindow() for the reasons the previous poster suggested. However, while technically doable, it is considered bad form to handle whether to save or actually destroy a window (ie prompting the user) during WM_DESTROY. Once DestroyWindow is called and the OS sends a WM_DESTROY message, the expectation is to prepare for the destruction of the window. So the workflow should have be like this:
Send a WM_CLOSE to the window handle in question. CloseWindow SHOULD do this, like DestroyWindow sends a WM_DESTROY message or ShowWindow sends a WM_SHOWWINDOW message. But again, since it doesn't, send the WM_CLOSE to the window.
Next, during the processing of the WM_CLOSE message, you can ask the user if they wish to save anything, or if they intend to actually close the window. If they cancel closing the window, simply return ZERO to tell the OS you processed the message. If the user indicates they wish to proceed, THEN you can call DestroyWindow OR simply pass the message to DefWindowProc, which the promptly do the same. Any saving of files should happen during the processing of WM_CLOSE. During the processing of WM_DESTROY, you should delete any dynamically allocated memory associated with the window and free resources. And finally FYI, WM_NCDESTROY is the last message a window receives.