It's bad enough for a guest to demolish the host's house; demolishing an unrelated person's house is taking it to a whole new level

Raymond Chen

“How do I destroy a window that belongs to another process?”

The Destroy­Window function will not destroy windows that belong to another thread, much less another process. The best you can do is post a WM_CLOSE message to the window to ask it nicely. The Def­Window­Proc function response to the WM_CLOSE message by destroying the window, but the window is free to add a custom handler for the WM_CLOSE message which rejects the request.

(If you are thinking of posting the WM_DESTROY message, then you’re the sort of person who prank-calls somebody pretending to be the police.)

If you want to distinguish between user-initiated requests to close the window (say, by clicking the X button in the corner), and your special, “No, really, just destroy the window” demand to close the window, you can invent a private message for this purpose.

#define WM_FORCECLOSE (WM_APP + 3141)
LRESULT CALLBACK VictimWndProc(HWND hwnd, UINT uMsg,
    WPARAM wParam, LPARAM lParam)
{
 switch (uMsg) {
 ...
 case WM_FORCECLOSE: DestroyWindow(hwnd); return 0;
 ...
 }
 return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
void ForceCloseWindow(HWND hwnd)
{
 PostMessage(hwnd, WM_FORCECLOSE, 0, 0);
}

Of course, this WM_FORCE­CLOSE message works only with windows specially designed to understand it.

“I can’t do that because the window I want to force closed belongs to some application I did not write, so I cannot modify its window procedure.”

This is another case of If it’s not yours, then don’t mess with it without permission from the owner. One of the rules of thumb for real life is that if something doesn’t belong to you, then you shouldn’t mess with it unless you have permission from the owner.

You need to work with the application vendor to come to some sort of agreement on how you can tell the application to close the window unconditionally. Otherwise, you’re even worse than the guest who visits a house and calls the demolition company to have the house destroyed. You’re the guy who calls the demolition company to order the destruction of some completely unrelated house.

How would you like it if a random person called the demolition company to destroy your house?

0 comments

Discussion is closed.

Feedback usabilla icon