Delete an HWND object
Asked Answered
V

2

6

I have a situation where when I receive a message I must delete a window just from the hWnd. I though this must be possible since CreateWindowEx creates an object by returning a HWND, I must be able to delete one.

Note : The hWnd lies on some other process.

Vanatta answered 22/9, 2012 at 12:17 Comment(1)
Instead of forcibly destroying it, cooperate with the other process to destroy the window so the other process can do proper cleanup. Otherwise it's like demolishing somebody else's house without permission.Telltale
C
7

Proper way is to send WM_CLOSE message to associated window or simply call DestroyWindow which will send WM_DESTROY message to window.

A thread cannot use DestroyWindow to destroy a window created by a different thread.

Difference between WM_CLOSE and WM_DESTROY:

After send WM_CLOSE a target application can prompt the user for confirmation, prior to destroying a window, by processing the WM_CLOSE message and calling the DestroyWindow function only if the user confirms the choice.

In other words, closing window using WM_CLOSE can be rejected, but it's considered "safer" then WM_DESTROY, because application can save ask for confirmation and save changes. However if you need to force closing use WM_DESTROY.

HWND struct pointers are managed by system, don't even try to delete them !

It does not matter which process owns window if using WM_CLOSE message.

Chapman answered 22/9, 2012 at 12:24 Comment(3)
You should not send WM_DESTROY. Call DestroyWindow if you want to forcibly delete a window object.Berri
-1 Only the thread that created the window can call DestroyWindow() on it. This is clearly stated in the DestroyWindow() documentation. The OP stated that the HWND in question belongs to a different process.Commonweal
Sending the WM_DESTROY message does not destroy the window. It merely prank-calls the window pretending to be the police.Telltale
S
3

Send the window a WM_CLOSE message with SendMessage.

Showman answered 22/9, 2012 at 12:19 Comment(1)
If the hWnd is from a different process, will the same work ?Vanatta

© 2022 - 2024 — McMap. All rights reserved.