I'm handling ESC
key in my application and when this key is received I wish to close the current window.
Should I simply call DestroyWindow(hWnd)
or should I SendMessage(WM_CLOSE, hWnd, 0, 0)
, or should I be closing the current window in some different way?
If you really do want to close the window, call the DestroyWindow function. Otherwise, simply return zero from the WM_CLOSE message, and the operating system will ignore the message and not destroy the window.
SendMessage: Sends a message and waits until the procedure which is responsible for the message finishes and returns. PostMessage: Sends a message to the message queue and returns immediately.
HWND is a "handle to a window" and is part of the Win32 API . HWNDs are essentially pointers (IntPtr) with values that make them (sort of) point to a window-structure data.
It is sent to the window procedure of the window being destroyed after the window is removed from the screen. This message is sent first to the window being destroyed and then to the child windows (if any) as they are destroyed. During the processing of the message, it can be assumed that all child windows still exist.
You should PostMessage(hWnd, WM_CLOSE, 0, 0)
. It puts the WM_CLOSE
message into the window's message queue for processing, and the window can close properly as the message queue is cleared.
You should use PostMessage
instead of SendMessage
. The difference is that PostMessage
simply puts the message into the message queue and returns; SendMessage
waits for a response from the window, and you don't need to do that in the case of WM_CLOSE
.
It is up to you which you use. Should the Esc key act just like clicking the close button, or should it definitely destroy the window?
The default implementation of WM_CLOSE
(as found in DefWindowProc
) calls DestroyWindow
, so if you're not handling WM_CLOSE
specifically then one is as good as another. But WM_CLOSE
doesn't necessarily have to call DestroyWindow
, though, so if the window in question handles it then it could do something else. For example, it could pop up a "Are you sure?"-type message box, or simply do nothing. DestroyWindow
will bypass all of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With