Search code examples
c++cwinapihwnd

Delete an HWND object


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.


Solution

  • 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.