33.2.2 Examining a Message Queue

There may be times when you need to examine the contents of a thread's message queue other than from within the thread's message loop. For example, if you have a window procedure that performs a lengthy drawing operation and you want the user to be able to interrupt the operation, you must periodically examine the message queue during the operation for mouse and keyboard messages. Otherwise, your application won't respond to user input until after the operation has completed. This is because the DispatchMessage function in the thread's message loop doesn't return until the window procedure finishes processing a message.

You can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function—both check a message queue for a message that matches the filter criteria and copy the message to an MSG structure. The main difference is that GetMessage doesn't return until a message matching the filter criteria is placed in the queue, but PeekMessage returns immediately regardless of whether a message is in the queue.

The following example shows how to use PeekMessage to examine a message queue for mouse clicks and keyboard input during a lengthy operation:

HWND hwnd;

BOOL fDone;

MSG msg;

/*

* Begin the operation and continue until it is complete

* or until the user clicks the mouse or presses a key.

*/

fDone = FALSE;

while (!fDone) {

fDone = DoLengthyOperation(); /* application-defined */

/*

* Remove any messages that may be in the queue. If the

* queue contains any mouse-button messages or key-down

* messages, end the operation.

*/

while (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) {

switch(msg.message) {

case WM_LBUTTONDOWN:

case WM_RBUTTONDOWN:

case WM_KEYDOWN:

.

. /* Perform any required clean-up. */

.

fDone = TRUE;

}

}

}

Windows includes other functions that allow you to examine the contents of a thread's message queue, including GetQueueStatus and GetInputState. GetQueueStatus returns an array of flags that indicate the types of messages in the queue. GetInputState returns TRUE if the queue contains mouse or keyboard messages. You can use either of these functions to determine whether the queue contains messages that you need to process.