Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In win32 C++ programming to close a window, should I call DestroyWindow(hWnd) myself or SendMessage(WM_CLOSE, hWnd, 0, 0)?

Tags:

winapi

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?

like image 495
bodacydo Avatar asked Aug 09 '13 21:08

bodacydo


People also ask

How do I close a Win32 window?

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.

What is the difference between SendMessage and PostMessage?

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.

Is Hwnd a pointer?

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.

What is the purpose of WM Destroy message?

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.


2 Answers

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.

like image 51
Ken White Avatar answered Sep 22 '22 05:09

Ken White


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.

like image 26
Tom Seddon Avatar answered Sep 22 '22 05:09

Tom Seddon