Why the peekMessage statement is required before Getmessage() for creating message queue?
Why peekmessage before getmessage?
7.6k Views Asked by Josh AtThere are 3 best solutions below
On
It's not. The two functions do different things.
PeekMessage(...) doesn't wait for a message to appear -- it gets the first one if it's there, optionally removing it from the queue as well, but returns false immediately there isn't one. It's more common in apps where you're doing some processing while waiting for messages, and can't just sit there and wait forever for the next message. Real-time games and such easily fall into this category.
GetMessage(...) waits til there's a message, and gets it. It's more efficient CPUwise, cause it's not constantly polling, but it will pause if there aren't any messages. It's more common in formy apps and other programs that don't require constant real-time processing to be going on.
On
There are multiple reasons for using PeekMessage before/instead of GetMessage:
- Ensuring the program will not hang until a message arrives - that's a bit redundant, cause you can directly use
PeekMessagewith thePM_REMOVEflag to poll the message queue and leave outGetMessagealtogether. - Using the function with
PM_NOREMOVEand deciding if you want to process and/or remove the message from the queue, or not. - Calling
IsWindowUnicodeon the returned messages' window handle and selecting eitherPeekMessageAorPeekMessageW. - Multiple of the above.
It's not required.
What you'll sometimes see, though, is a thread that isn't ready to process messages yet, but it wants to be able to receive them in its message queue. New threads do not have message queues right away, but calling
PeekMessageis sufficient to create the message queue. It returns immediately since there is no message, and that allows the thread to continue getting itself ready. In the meantime, other threads can start queuing messages for the new thread. Once the new thread is ready, it callsGetMessageto either retrieve the first message off the queue, or to wait for a message to be put onto the queue.