Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my demo kinda app

case WM_CLOSE:
    DestroyWindow(hndl);
    return 0;

and

case WM_CLOSE:
    PostQuitMessage(0);
    return 0;

do the same. What's different behind the curtains when calling each? Is DestroyWindow more direct, where as PostQuitMessage has to go through the getmessage loop returning false?

like image 572
rails_has_elegance Avatar asked May 25 '13 11:05

rails_has_elegance


2 Answers

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.

like image 85
chris Avatar answered Oct 15 '22 04:10

chris


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;
like image 24
Hans Passant Avatar answered Oct 15 '22 05:10

Hans Passant