Jump to content

Message loop in Microsoft Windows

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Charliearcuri (talk | contribs) at 18:14, 14 June 2009 (External links: fixing misdirected link (should be "Message Queue" related but was pointing to "Cursor Overview")). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Microsoft Windows programs are event-based. They act upon messages that the operating system posts to the main application thread. These messages are received by the application by repeatedly calling the GetMessage (or PeekMessage) function in a section of code called the "event loop." The event loop typically appears as follows:

 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPSTR lpCmdLine, int nCmdShow)
 {
   MSG msg;
   while (GetMessage(&msg, NULL, 0, 0) > 0) {
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }
   return msg.wParam;
 }

Though not strictly required, it's conventional for the event loop to call TranslateMessage and DispatchMessage, which transfers the message to the callback procedure associated with the window the message refers to.

Modern graphical interface frameworks, such as Visual Basic and Qt do not typically require applications to directly access the Windows message loop, but instead automatically route events such as keypresses and mouse clicks to their appropriate handlers as defined within the framework. Underlying these frameworks, however, the message loop can again be found, and can typically be accessed when more direct control is required.

Note: Notice the greater than zero in the while condition in the example. Even though GetMessage return value is defined as BOOL, in Win32, the return value should be actually treated as int. That is because the -1 indicates error, 0 (zero) indicates the quit message, and if a message is found, non-zero value is returned (probably always positive, but the documentation does not say explicitly that — follow the external link for the GetMessage function below for the details).