c++windowswinapi

Will GetMessage() return -1 in main message loop?


According to the GetMessage API from MSDN Library, it might returns -1 when there is an error. The document provides a code snippet of common error that should be avoid:

while (GetMessage( lpMsg, hWnd, 0, 0)) ...

Document says:

The possibility of a -1 return value means that such code can lead to fatal application errors. Instead, use code like this:

BOOL bRet;
while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
}

My question is, in every sample code, including default application created from Visual Studio, from Microsoft, the main message loop looks like below:

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

Notice that the 2nd parameter of GetMessage above is NULL. If the code above is valid, does this mean that GetMessage here will NEVER returns -1 so that dealing with return value of -1 is not necessary?


Solution

  • Given that VS gives you wrong code by default, and nobody seems to care, it is very likely that this causes no trouble in current versions of Windows.

    It is possible that some future version of GetMessage will return -1. However, since the erroneous code must be in so many existing applications by now, this would break a huge amount of existing code. Given Microsoft's dedication to backwards compatibility, I think it's highly unlikely that they'll change the behaviour of GetMessage that so many programs are relying upon.

    And in spite of all that, you should still follow the documentation.