Jump to content

WindowProc, WM_DESTROY and PostQuitMessage(0)

nickl

I was recently playing around with learning about Win32 and C++. MSDN has a code sample that simply opens a blank window, using CreateWindowEx, etc.

I was learning about how the window is closed, and this is my understanding of the process.

When the X button is clicked or Alt+F4 is pressed, a WM_CLOSE message is put on the message queue to the window.

By default the WM_CLOSE message is evaluated by DefWindowProc function and posts a WM_DESTROY message onto the message queue, after the removal of the window.

The WM_DESTROY should have a special case in your switch inside of your WindowProc function, which is supposed to call the PostQuitMessage(0) function, which would then put a WM_QUIT message on to the message queue.

This WM_QUIT message is then evaluated by the GetMessage function in the condition of the while loop that runs the TranslateMessage and DispatchMessage that would normally call your WindowProc function, but when WM_QUIT is taken off of the message queue the GetMessage function evaluates to 0, stopping the loop. 

 

I am now curious what happens when I comment out the PostQuitMessage inside of the WM_DESTROY case of my switch inside WindowProc.

When I do so, it opens the window as usual, and when I click the X button, it closes the window as I would expect. The task also seems to end in task manager. However, in Visual Studio, it seems to think that the program is still running until I click the stop debugging button.

 

What is happening in this case?

What I think is happening is that WM_CLOSE is being put on the message queue, being evaluated (by default) to WM_DESTROY, after the window is destroyed and not bring drawn. However, due to me commenting out the PostQuitMessage function, the Translate-/Dispatch-Message function loop isn't stopping, and not terminating the program since the wWinMain function never reaches the return 0; statement after the while loop. Does this explain the fact that VS thinks that debugging isn't over? And if this is the case, why does task manager not seem to recognize this?

 

However, when I stop the debugging, Visual Studio claims that the program ended with exit code 0.

So thanks for reading guys, if this post sucked, I'm not sure what you can do, but if you liked it, go 'head and hit that like button, or maybe add me as a friend. Otherwise, go subscribe to LinusTechTips on YouTube, follow them on Twitch, follow @LinusTech on Twitter, and support them by using their affiliate code on Amazon, buying a cool T-shirt, or supporting them directly on this community forum.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×