Sign in to follow this  
MARS_999

GetMessage vs. PeekMessage

Recommended Posts

MARS_999    1627
I was using PeekMessage but without any mouse movements or button events, and now I am using them and with PeekMessage I get delays or missed events... When I change to a GetMessage() all is gone? This is for a game so speed is important shouldn't I be using PeekMessage and if so what might be the issue... Thanks

Share this post


Link to post
Share on other sites
outRider    852
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this