开发者

How can I detect window destruction from the main thread?

开发者 https://www.devze.com 2023-02-11 06:29 出处:网络
Typically, the window procedure for a \"main\" window class would call PostQuitMessage in response to a WM_DESTROY message.

Typically, the window procedure for a "main" window class would call PostQuitMessage in response to a WM_DESTROY message.

I would prefer to have the main thread decide when it wants to terminate based on the lifespan of the window(s) it creates. This way, whatever window class I choose to be the main window can have a generic window procedure that doesn't have PostQuitMessage in it.

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);

    if(msg.hwnd == hWnd && msg.message == WM_DESTROY)
    {
        PostQuitMessage(0);
    }
}

The above is my attempt, but the WM_DEST开发者_如何学JAVAROY message is never posted to the message queue, it seems to be internal to the window procedure.

Is there some way to accomplish this?


WM_DESTROY is being sent rather than posted which is why it never lands in the message queue. If it ends up in the WndProc, and it doesn't come through the message pump, what other explanation could there be?

Window handles are destroyed by calling DestroyWindow which, in turn, sends the WM_DESTROY message directly to the WndProc.

I think you will need to find some other way for your potential main windows to decide which one is the one that brings the curtain down when it is destroyed.


I have found a method that seems to do what I want. I was inspired by http://www.autoitscript.com/forum/topic/66508-peekmessage-and-wm-close/ by Valik to investigate subclassing.

First, I replace the Window Procedure of the window that I want to a special "PostQuitMessage" procedure.

Original_WindowProc = (WNDPROC)GetWindowLongPtr(hWnd, GWL_WNDPROC);
SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)&WindowProc);

The window procedure looks like this:

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg,  WPARAM wParam,  LPARAM lParam)
{
    if(uMsg == WM_DESTROY)
    {
        PostQuitMessage(0);
    }

    return CallWindowProc(Original_WindowProc, hWnd, uMsg, wParam, lParam);
}

This allows me to convert any window class (including system ones) into the main window for my application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号