Win32: The Message Loop

The Message Loop

This Win32 video covers the windows message loop. The message loop is the central processing area code for Win32 programs. Simple applications like our Lesson 1 program have a single thread of execution that runs inside the message loop and processes messages that result from events like a key press or mouse click. Attached to the thread is a message queue where messages are added as events occur. The thread checks its queue until it finds a message. When the thread gets a message, the message is passed to the appropriate windows callback function where it is processed.

The code below shows the message loop from our Win32 Lesson 1 program. In this while loop, GetMessage() is called to extract the message from the message queue. If GetMessage() is successful in getting a message, it is put into the object msg. Once a message is retrieved, it is passed into the translate functions, which we will ignore for now. Eventually, the message is passed into DispatchMessage(), which sends the message to the callback function for the appropriate window. The only callback function in this program is WndProc(). The message loop will terminate when GetMessage returns FALSE. This happens after PostQuitMessage() is called inside of WndProc().

WndProc() is the callback associated with our only application window. The window is bare except for two menu items in the menubar: File and Help. These menu items have submenus with a single item in each: Exit and About, respectively.

The code for WndProc() handles three types of messages and is shown below: WM_COMMAND, WM_PAINT, and WM_DESTROY. Any other message is sent to the default branch of the switch statement, where it is handled by the default handler DefWindowProc().

Both of our menu commands are handled inside of the WM_COMMAND branch and correspond to the wmId values of IDM_ABOUT and IDM_EXIT. These are passed in by selecting About and Help from our menubar. The first pops up the about message box and the second calls DestroyWindow(). DestroyWindow posts the message WM_DESTROY to the message queue, which is handled here in the appropriate branch with a call to PostQuitMessage(). After the call to PostQuitMessage(), the message loop exits.