The Message Loop

Since your application receives input through an application queue, the chief feature of any Windows application is the “message loop.” The message loop retrieves input messages from the application queue and dispatches them to the appropriate windows.

Figure 13.2 shows how Windows and an application collaborate to process keyboard input messages. Windows receives keyboard input when the user presses and releases a key. Windows copies the keyboard messages from the system queue to the application queue. The message loop retrieves the keyboard messages, translates them into an ANSI character message, WM_CHAR, and dispatches the WM_CHAR message, as well as the keyboard messages, to the appropriate window function. The window function then uses the TextOut function to display the character in the client area of the window.

Windows can receive and distribute input messages for several applications at once. As shown in Figure 13.3, Windows collects all input, in the form of messages, in its system queue. It then copies each input message to the appropriate application queue. The message loop in each application retrieves messages and dispatches them, through Windows, to each application's appropriate window function.

In contrast to keyboard input messages, which the application must retrieve from its message queue, Windows sends window-management messages directly to the appropriate window function. Figure 13.4 shows how Windows sends window-management messages directly to a window function. After Windows carries out a request to destroy a window, it sends a WM_DESTROY message directly to the window function, bypassing the application queue. The window function must then signal the main function that the window is destroyed and the application should terminate. It does this by copying a WM_QUIT message into the application queue by using the PostQuitMessage function.

When the message loop retrieves the WM_QUIT message, the loop terminates and the main function exits.