INF: Posting Frequent Messages Within an Application

ID Number: Q40669

2.x 3.00

WINDOWS

Summary:

The object-oriented nature of Windows programming can create a

situation in which an application posts a message to itself. When such

an application is designed, care must be taken to avoid posting

messages so frequently that system messages to the application are not

processed. This article discusses two methods of using the PeekMessage

function to combat this situation.

More Information:

In the first method, a PeekMessage loop is used to check for system

messages to the application. If none are pending, the SendMessage

function is used from within the PeekMessage loop to send a message to

the appropriate window. The following code demonstrates this

technique:

while (fProcessing)

{

if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))

{

if (msg.message == WM_QUIT)

break;

/* process system messages */

}

else

{

/* perform other processing */

...

/* send WM_USER message to window procedure */

SendMessage(hWnd, WM_USER, wParam, lParam);

}

}

In the second method, two PeekMessage loops are used, one to look for

system messages and one to look for application messages. PostMessage

can be used from anywhere in the application to send the messages to

the appropriate window. The following code demonstrates this

technique:

while (fProcessing)

{

if (PeekMessage(&msg, NULL, 0, WM_USER-1, PM_REMOVE))

{

if (msg.message == WM_QUIT)

break;

/* process system messages */

}

else if (PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_REMOVE))

/* process application messages */

}

An application should use a PeekMessage loop for as little time as

possible. To be compatible with battery-powered computers and to

optimize system performance, every Windows application should inform

Windows that it is idle as soon and as often as possible. An

application is idle when the GetMessage or WaitMessage function is

called and no messages are waiting in the application's message queue.