1.1.2 Translating Messages

In general, a WinMain function should use the TranslateMessage function to translate every message, not just virtual-key messages. Although TranslateMessage has no effect on other types of messages, it guarantees that keyboard input is translated correctly.

The following example illustrates the typical main message loop that a WinMain function uses to retrieve messages from the application's message queue and dispatch them to the application's window procedures:

int PASCAL WinMain(hinst, hPrevInst, lpCmdLine, ShowCmd)
HINSTANCE hinst;
HINSTANCE hPrevInst;
LPSTR lpCmdLine;
int ShowCmd;
{
    MSG msg;
     .
     .
     .
    


while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

An application that uses accelerator keys must load an accelerator table from the resource-definition file by using the LoadAccelerators function and then trans-late keyboard messages into accelerator-key messages by using the TranslateAccelerator function. For more information about accelerator keys, see the Microsoft Windows Guide to Programming.

The main message loop for an application that uses accelerator keys should have the following form:

while (GetMessage(&msg, NULL, 0, 0)) {
    if (TranslateAccelerator(hwnd, haccel, &msg) == 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
     }
}
return msg.wParam;

The TranslateAccelerator function must appear before the standard TranslateMessage and DispatchMessage functions. Furthermore, because TranslateAccelerator automatically dispatches the accelerator-key message to the appropriate window procedure, the TranslateMessage and DispatchMessage functions should not be called if TranslateAccelerator returns a nonzero value.