In general, a main 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 any keyboard input is translated correctly.
The following program fragment illustrates the typical loop that a main function uses to pull messages from the queues and dispatch them to window functions:
int PASCAL WinMain(hInstance, hPrevInstance, lpCmdLine, nShowCmd)
HANDLE hInstance;
HANDLE hPrevInstance;
LPSTR lpCmdLine;
int nShowCmd;
{
MSG msg;
.
.
.
while (GetMessage((LPMSG)&msg, NULL, 0, 0))
{
TranslateMessage((LPMSG)&msg);
DispatchMessage((LPMSG)&msg);
}
exit(msg.wParam);
}
Applications that use accelerator keys must load an accelerator table from the resource file by using the LoadAccelerator function, and then translate keyboard messages into accelerator-key messages by using the TranslateAccelerator function. The main loop for applications that use accelerator keys should have the following form:
while (GetMessage((LPMSG)&msg, (HWND)NULL, 0, 0))
{
if (TranslateAccelerator(hWindow, hAccel, ((LPMSG)&msg) == 0)
{
TranslateMessage((LPMSG)&msg);
DispatchMessage((LPMSG)&msg);
}
}
exit(msg.wParam);
The TranslateAccelerator function must appear before the standard TranslateMessage and DispatchMessage functions. Furthermore, since TranslateAccelerator automatically dispatches the accelerator message to the appropriate window function, the TranslateMessage and DispatchMessage functions should not be called if TranslateAccelerator returns a nonzero value.