Win32 Application Wizard suggests wrong GetMessage usage

Started by Romashka, June 20, 2009, 12:03:06 AM

Previous topic - Next topic

Romashka

Win32 Application Wizard wizard generates this code in HelloWorld application:
    /* Pump messages until we are done */
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }


This is common but wrong usage of GetMessage.
A quote from MSDN:
Quote
Warning 

Because the return value can be nonzero, zero, or -1, avoid code like this:
while (GetMessage( lpMsg, hWnd, 0, 0)) ...

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);
    }
}


I suggest to fix this so newbies don't get started with wrong code.
Either the above code from MSDN or simple
while (GetMessage(&msg, NULL, 0, 0) > 0)
will be OK.

Pelle

AFAIK, Microsoft changed the documentation for GetMessage() in recent years. Maybe I change this some day...
/Pelle

Romashka

I've checked this in an ancient (Windows 95 times) Win32 Programmer's Reference from Microsoft - and it has the same return values description as on MSDN, but there are many incorrect (as in current HelloWorld wizard) code examples in that reference and MSDN, so it looks like documentation guys from Microsoft don't check their own information. :)
Anyway this is not really important, just wanted to inform you when I saw it, to not forget, as I never start any project with a wizard anyway.