Reputation: 33813
I have a little problem. I will show you an example firstly, then I will tell you what the problem.
Example:
while(GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
That example work correctly, but if the parameter 2 in "GetMessage" function changed to a handle name of window as the following:
Example2: after changed
while(GetMessage(&msg, Hwnd, 0, 0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Will occurs a little problem when exit the program. still the program works in processes list. And need to select it then click on end process button to terminate the program
And now, Is there a difference between add (NULL or window handle)?
Upvotes: 3
Views: 541
Reputation: 33813
There are two ways to solve that problem:
1- Passing a NULL
value to the GetMessage
function instead of the window. handle.
GetMessage(&msg, NULL, 0, 0)
2- Because the return value can be nonzero, zero, or -1, the possibility of a -1 return value if hWnd is an invalid parameter (such as referring to a window that has already been destroyed) means that such code can lead to fatal application errors. Instead, use code like this.
BOOL gmRet;
while ((gmRet = GetMessage(&msg, hWnd, 0, 0)) != 0) {
if (gmRet == -1) {
return 0;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Upvotes: 0
Reputation: 8801
The fundamental difference between the two examples you presented is how the messages are handled by your application. The first example will pull messages from the message queue for any of the windows you may create within the application. The later example will pull message only from the window associated with the handle that is passed to the function. You could potentially create many windows within your application. If you were only interested in capturing messages for a particular window, that parameter will serve to limit the messages that are translated and dispatched to the window procedure function. However, if you plan to create only a single window, the difference is negligible.
Upvotes: 0
Reputation: 9838
The problem you encounter in your second example is that after your window is destroyed, the window handle you supply to GetMessage()
is no longer valid. Every subsequent call returns an error to notify you of that (with GetLastError()
giving ERROR_INVALID_WINDOW_HANDLE
), but the code doesn’t handle this case and so ends up in a busy loop forever.
This is why the MSDN Library page for GetMessage()
advises against using while (GetMessage(...))
.
Upvotes: 6