5

This is somewhat of a general question regarding Windows programming:

Are Window messages "reliable"?

For example (these are just examples):

  • Can you be certain that a WM_MOUSEMOVE will happen before a cursor enters your screen?

  • Can you be certain that you will get a WM_DEVICECHANGE message if a device is inserted?

  • Can you be certain that you will receive a WM_KILLFOCUS message if your window loses focus?

Or, in other words: Can you be certain that you'll get the appropriate message at the appropriate times, or do you always have to code defensively in case that, somehow, you might miss a message for no apparently documented reason?


Example:

  • It is guaranteed (AFAIK) that a file system filter driver will not "miss" a file operation or change notification.

  • By contrast, it is not guaranteed that ReadDirectoryChangesW will not miss a notification. In fact, it can miss quite a few if its buffer overflows.

Note:

I am not talking about a situation against an adversary (e.g. someone hijacking your window procedure or installing a hook/filter); that would pretty much invalidate any guarantee. I'm only asking about obscure situations that could really happen even if no one meant anything bad intentionally, like if some random buffer overflows, if someone uses SendInput, etc., assuming you have control of your own code.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • 2
    This is NOT what "reliable" means. "Reliable" means that you can be certain that either the message was successfully delivered OR an error is reported to the sender, messages cannot be lost silently. – Ben Voigt May 24 '11 at 17:38
  • In general, no you can't. For specific messages, yes you can. –  May 24 '11 at 17:40
  • @Ben: That's not what *I* meant by "reliable". ;) I'll put an example to illustrate my point. – user541686 May 24 '11 at 17:49
  • The window message queue also has a maximum length (from [the docs](http://msdn.microsoft.com/en-us/library/ms644944.aspx): "There is a limit of 10,000 posted messages per message queue."), `PostMessage` can fail if the queue is full. – Ben Voigt May 24 '11 at 18:22

1 Answers1

3

No you cannot be certain that a given message will be delivered in a specific order. Here are a couple of reasons why not

  • Messages can be sent progamatically and this can be used to simulate "impossible" scenarios like a WM_KEYUP followed by a WM_KEYDOWN.
  • Another routine could sub-class your window and selectively intercept messages and not send them on to your WNDPROC

It's best to code defensively around any scenarios where ordering is important

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454