WINAPI GetKeyboardState behavior modified by GetKeyState when application is out of focus?

Viewed 1051

When calling the WINAPI command GetKeyboardState(aByteArray) from a WPF application (and assumedly other applications as well), holding down the SHIFT key is correctly detected only when the application has focus. When the application does not have focus, aByteArray[VK_SHIFT] is 0 after the method call.

However, if GetKeyState(aVKCode) is called immediately prior to GetKeyboardState(aByteArray), for any value of aVKCode, even if the return value is discarded, then GetKeyboardState(aByteArray) will provide the correct non-zero state of the held SHIFT key when the application is not in focus.

This behavior is counterintuitive and appears to have caused many programmers grief. I believe that there is relevant information in the documentation for GetKeyboardState which reads:

The status changes as a thread removes keyboard messages from its message queue. The status does not change as keyboard messages are posted to the thread's message queue, nor does it change as keyboard messages are posted to or retrieved from message queues of other threads.

Potentially, GetKeyState() interacts with the message queue in such a way that it must be called prior to GetKeyboardState() in order for GetKeyboardState() to behave as desired. However, I am unfamiliar with the concept of the message queue and how items are added and removed by Windows, and so I thought I'd ask here. Can anyone explain why a call to GetKeyboardState() alone cannot capture the SHIFT key being held without application focus?

1 Answers
Related