What's the logical difference between PostQuitMessage() and DestroyWindow()?

前端 未结 3 499
暗喜
暗喜 2021-01-01 17:56

In my demo kinda app

case WM_CLOSE:
    DestroyWindow(hndl);
    return 0;

and

case WM_CLOSE:
    PostQuitMessage(0);
    r         


        
相关标签:
3条回答
  • 2021-01-01 18:32

    PostQuitMessage doesn't necessarily mean the end of application. It simply posts WM_QUIT to the message loop and allows you to exit from the message loop, so in most cases, this means the end of the application. However, in a multithread application, if you have the message loop for each thread created, PostQuitMessage only closes that thread.

    As a side note, if you ever need more lines of code to execute after the message loop (such as further clean-up), PostQuitMessage is a better way to go, because DestroyWindow destroys the window without going through the message loop, ignoring whatever clean-up codes remaining after the message loop. Some may call it a not-so-good coding practice, but sometimes you can't avoid situations like that.

    0 讨论(0)
  • 2021-01-01 18:42

    DestroyWindow destroys the window (surprise) and posts a WM_DESTROY (you'll also get a WM_NCDESTROY) to the message queue. This is the default behaviour of WM_CLOSE. However, just because a window was destroyed does not mean the message loop should end. This can be the case for having a specific window that ends the application when closed and others that do nothing to the application when closed (e.g., an options page).

    PostQuitMessage posts a WM_QUIT to the message queue, often causing the message loop to end. For example, GetMessage will return 0 when it pulls a WM_QUIT out. This would usually be called in the WM_DESTROY handler for your main window. This is not default behaviour; you have to do it yourself.

    0 讨论(0)
  • 2021-01-01 18:49

    Neither snippet is correct. The first one will do what the default window procedure already does when it processes the WM_CLOSE message so is superfluous. But doesn't otherwise make the application quit, it should keep running and you'd normally have to force the debugger to stop with Debug + Stop Debugging. If you run it without a debugger then you'll leave the process running but without a window so you can't tell it is still running. Use Taskmgr.exe, Processes tab to see those zombie processes.

    The second snippet will terminate the app but will not clean up properly since you don't pass the WM_CLOSE message to the default window procedure. The window doesn't get destroyed. Albeit that the operating system will clean up for you so it does all come to a good end, just without any bonus points for elegance.

    The proper way to do it is to quit when your main window is destroyed. You'll know about it from the WM_DESTROY notification that's sent when that happens:

    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    
    0 讨论(0)
提交回复
热议问题