Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
sam Avatar asked Mar 13 '11 08:03

sam


2 Answers

You should follow the rules specified in the MSDN documentation for GetMessage(). It's painless to do so and it's not as if you have large numbers of message loops scattered about your code.

The Visual Studio team are separate to the Windows team and they make the same mistakes as everyone else!

I reality I can't ever imagine GetMessage() returning an error, but that is the nature of error handling – that doesn't mean you shouldn't handle errors properly.

like image 197
David Heffernan Avatar answered Sep 19 '22 15:09

David Heffernan


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.

like image 39
Thomas Avatar answered Sep 18 '22 15:09

Thomas