HOWTO: Post Frequent Messages Within an Application

ID: Q40669


The information in this article applies to:
  • Microsoft Windows Software Development Kit (SDK)
  • Microsoft Win32 Software Development Kit (SDK)
  • Microsoft Windows 2000


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-based 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.

Additional query words:

Keywords : kbNTOS kbWinOS2000 kbSDKWin32 kbGrpUser kbWinOS kbWndw kbWndwMsg kbWndwProc
Version : WINDOWS:
Platform : WINDOWS
Issue type : kbhowto


Last Reviewed: February 1, 2000
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.