This is not a simple thing to do. Before doing it you should think if you really need it. Usually you don't need to know how many messages are there in the queue. There is no a completely non-intrusive way to know it — maybe because it is never required; and the code based on this knowledge might be incorrect — all messages should be properly processed.
First, before posing this task, bear in mind that not all messages are queued. There are queued messages and nonqueued messages. See
http://msdn.microsoft.com/en-us/library/ms644927%28v=VS.85%29.aspx[
^]. The mechanism of using both is kind of very cunning. For example,
WM_PAINT
message goes outside the queue because it optimizes
Invalidate
requests: if a windows is fully or partially invalidated, the message data is modified to merge ("OR", theory-set disjunction operation) old and new requests to keep no more than on non-handled
WM_PAINT
message to avoid excessive re-rendering.
Now, the way to check is there is a message of certain type in the message queue, you can use the API
PeekMessage
, see the code sample here:
http://msdn.microsoft.com/en-us/library/ms644928%28v=VS.85%29.aspx[
^], the description of the function here:
http://msdn.microsoft.com/en-us/library/ms644943(v=VS.85).aspx[
^]. See also the article "Why to use PeekMessage":
http://msdn.microsoft.com/en-us/library/ms644928(v=VS.85).aspx#3[
^].
Now, the trick is: if you use
PeekMessage
in the UI thread repeatedly, you will pause processing message during this operation, but it will return the same very message until you break the loop unless you remove the message (see the last parameter of the function). But if you remove the message to get to new message every time and ultimately count them all, you would disrupt the normal message processing!
So, what would be the work-around? You could get all messages from the queue using
PeekMessage
with remove option, learn the results (count/classify them or whatever) and put all the messages in some internal container. You will need them to stick them back in the queue using
PostMessage
, see
http://msdn.microsoft.com/en-us/library/ms644944%28v=VS.85%29.aspx[
^].
I still wonder: why would you need all that?
—SA