Jump to content

  • Log In with Google      Sign In   
  • Create Account


outRider

Member Since 04 Jul 2000
Offline Last Active May 17 2014 11:45 PM
-----

#2881897 GetMessage vs. PeekMessage

Posted by outRider on 26 January 2005 - 04:58 PM

You're using PeekMessage incorrectly perhaps? First, make sure you're calling it right. Don't provide a window handle or min and max filters unless you know you need to. The only reason to use PeekMessage over GetMessage is to do stuff even though you have no messages to respond to.

Your typical GetMessage loop:


while (GetMessage(...) > 0)
{
TranslateMessage();
DispatchMessage();
}





GetMessage blocks, meaning every time you call it your program stays inside it until it recieves a message. The only time the body of the loop is executed is when you have messages, otherwise your program is somewhere inside GetMessage.

The equivalent PeekMessage loop:


while (true)
{
while (PeekMessage(..., PM_REMOVE) == FALSE) {}

if (Msg.message == WM_QUIT)
break;

TranslateMessage();
DispatchMessage();
}





The above does what GetMessage does, hence it's not useful. Here's something better:


while (true)
{
if (PeekMessage(..., PM_REMOVE) == TRUE)
{
if (Msg.message == WM_QUIT)
break;

TranslateMessage();
DispatchMessage();
}

// Do your stuff here
}





But that only processes one message per iteration through your main loop. If you're doing a game, Windows messages can get clogged up because you're not clearing them fast enough. Here's something that addresses that:


while (true)
{
while (PeekMessage(..., PM_REMOVE) == TRUE)
{
if (Msg.message == WM_QUIT)
break;

TranslateMessage();
DispatchMessage();
}

// Do your stuff here
}





The above clears the message pump before dealing with your main loop.

You need to figure out what kind of application you're writing. Are you writing an app that needs frequent updating regardless of user interaction or is your app primarily responding to events? Most games are doing something regardless of whether or not the user is providing input, so you can't use either of the first two examples. But in your case if you still rely on Windows messages for input and such you should either use the 3rd snippet and poll for input in the 'do stuff here' section or use the 4th snippet and clear the message queue each iteration.


PARTNERS