NO

Author Topic: Win32 Application Wizard suggests wrong GetMessage usage  (Read 3381 times)

Romashka

  • Guest
Win32 Application Wizard suggests wrong GetMessage usage
« on: June 20, 2009, 12:03:06 AM »
Win32 Application Wizard wizard generates this code in HelloWorld application:
Code: [Select]
    /* 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:
Code: [Select]
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:
Code: [Select]
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
Code: [Select]
while (GetMessage(&msg, NULL, 0, 0) > 0)will be OK.

Offline Pelle

  • Administrator
  • Member
  • *****
  • Posts: 2266
    • http://www.smorgasbordet.com
Re: Win32 Application Wizard suggests wrong GetMessage usage
« Reply #1 on: June 21, 2009, 01:13:39 PM »
AFAIK, Microsoft changed the documentation for GetMessage() in recent years. Maybe I change this some day...
/Pelle

Romashka

  • Guest
Re: Win32 Application Wizard suggests wrong GetMessage usage
« Reply #2 on: June 21, 2009, 06:29:02 PM »
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.