Since all windows in a program can receive messages, one of the jobs of the WinMain function is to read messages from the program queue and dispatch them to the appropriate window. This is done with a “message loop.”
A message loop is a while statement that retrieves messages and dispatches them. A Windows program retrieves messages with the GetMessage function. GetMessage is called repeatedly until it returns a NULL, which means the application is terminating. The following code is essential in the WinMain function.
MSG msg;
.
.
.
while (GetMessage(&msg, NULL, NULL, NULL)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
The GetMessage function retrieves an event in the form of a message (MSG) structure. (You can filter the type of messages to accept. The NULL arguments accept all messages.) The message contains information such as the type of message, the time the message was placed in the queue, the mouse coordinates, and the window to which the message is directed.
The message structure is then passed back to Windows with the
TranslateMessage function. If the event was a keystroke message, the
ANSI value of the key is placed in the message structure.
The final part of the message loop, DispatchMessage, directs Windows to send each message to the appropriate window function. The window function then processes the message, depending on the message type.
NOTE:
Windows is a nonpreemptive multitasking system. This means Windows cannot take control from a program. The program must yield control before Windows can reassign control to another program. To ensure that all running programs have equal access, GetMessage automatically yields control when there are no messages in a program queue. This means that because there is no work for the program to do, Windows can give control to another program.