First version
First, let's write a message loop that's easiest to think about:
MSG msg
while( GetMessage(&msg,NULL,0,0) )
{
TranslateMessage (&msg);
DispatchMessage(&msg);
}
The first parameter of the GetMessage function is a pointer to the MSG structure. The second parameter is a window handle (HWND) that gets the message for the specified window, and fills in null to get the message or thread message for all windows of the current thread. The last two parameters are Wmsgfiltermin and Wmsgfiltermax, which are used to get the specified message and 0 to get all the messages.
The TranslateMessage function generates a corresponding WM_CHAR message based on the time of the Wm_keyup,wm_keydown.
The DispatchMessage function handles the window message to the appropriate window procedure (WINDOWPROC).
The above message loop, in most cases, can work very well, especially in general to write a small program, written in the form above completely no problem. But occasionally there may be some problems, so please go on and see what improvements are available.
Second version
If we take a closer look at the description of the GetMessage function on MSDN, we can see that MSDN points out that the while (GetMessage) is wrong and gives the following form:
BOOL bRet;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
In addition to returning 0 when the Wm_quit message was received, GetMessage returned 1 in the event of an error. In most cases, even if the error occurred, MSG saved the last message, a message was processed two times, I think most people will not be aware of it. However, if we want to write a framework program like MFC or self-discipline, the robustness of this program can not be ignored.
Before continuing with the next version of the improvement, now imitate MFC or WTL, do a pretranslatemessage:
BOOL PreTranslateMessage(LPMSG pMsg)
{
return FALSE;
}
BOOL bRet;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else if (!PreTranslaeMessage(&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}