Windows message loops and WTL

1.6k views Asked by At

I'm trying to understand the way WTL works, and message loops are confusing me right now.

For example this code fragment: link

The window is first created and after that the message pump is started. How come it works? Isn't the CreateEx, UpdateWindow and so on supposed to send their own invisible messages like WM_CREATE/WM_PAINT/WM_NCPAINT? Where are they thrown if the message pump is not initialized? What happens if you create a window, start message loop, then close the window, but want to create a new one in it's place? PostQuit exits the loop and you have to create a new one?

2

There are 2 answers

6
Hans Passant On BEST ANSWER

Understanding the difference between posting messages (PostMessage) and sending messages (SendMessage) is important here. Windows calls the window procedure directly for sent messages, they are not dispatched by the message loop. Which is how WM_CREATE and WM_SHOWWINDOW can be processed before the message loop is started. WM_QUIT, WM_PAINT, WM_KEYDOWN and WM_MOUSEMOVE are examples of messages that are posted.

0
AudioBubble On

Regarding the message sending, CreateWindow sends the message directly, as if SendMessage were used. If you've done much Windows programming, you'll probably have sent messages to controls directly in this way, and had things happen immediately without needing the message pump to run; Windows will do this itself, too.

As for the PostQuitMessage issue, the usual tactic is to have some other check in the message loop to see if the application should exit. For example, rather than posting a quit message on window close and waiting for WM_QUIT in the message loop, you could maintain a counter of open windows then just quit if there are 0 open windows.

There is nothing magic about WM_QUIT, except for the convenient way you can post it with PostQuitMessage and easily check for it with the GetMessage (etc.) functions. You are free not to use it and decide to exit your program for some other reason.