Spice
Spice

Reputation: 256

WinAPI Documentation contradicting itself?

So I've just been looking through the Windows Documentation just to read up on some stuff and to get a broader understanding as to how the WinAPI works and so on, however, I couldn't help but notice the fact that the documentation seems to contradict itself in some cases and I need some reassurance as to which way of doing things is really the correct way of doing things. The specific example I'm looking at deals with the GetMessage() function and the 'Window Message Loop'.

The first site (Window Messages) states that the correct syntax for the message loop is the following...

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

(if you scroll down it's right before the 'Posted Messages versus Sent Messages' heading near the bottom of the page)

The doc explains that the WM_QUIT message causes the function to return 0 which in turn will lead to the while loop breaking and the application terminating. Otherwise, the function will return a non-zero value causing the while loop to continue.

The second site (The one for the GetMessage() function) explicitly states to avoid writing code like the one previously explained. This site says that the GetMessage() function can return a value of -1 in case of an error and that using code like this

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

would cause the application to continue running if the function returns -1 even though it should handle the error and terminate appropriately. The valid implementation for the message loop should then be 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 have always done it this way so that I could catch the -1 error if there happens to be one. But after seeing Microsoft basically make the supposed mistake themselves now I am confused. So which is it Microsoft? Is it valid or not valid to do this?

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

Upvotes: 1

Views: 107

Answers (1)

Weather Vane
Weather Vane

Reputation: 34583

You are not comparing like with like. The documentation states that -1 is returned if hWnd is invalid.

In the first case the loop is passing NULL

while (GetMessage(&msg, NULL, 0, 0))

and so -1 cannot be returned. But in the second example

while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)

the variable hWnd is being passed so there can be an error.

Upvotes: 3

Related Questions