Physical Key State

◇◆丶佛笑我妖孽 提交于 2019-12-04 20:46:40

You aren't giving the window manager enough time to process the input you just injected. Until it reaches the "update key states for GetAsyncKeyState" part of the code, GetAsyncKeyState will report the old value. (In particular, it won't reach that point until all low-level keyboard hooks have had a chance to inspect the action and possibly reject it.)

In other words, your code has a race condition, and that is what you are observing.

You are getting a bit confused here. In fact GetAsyncKeyState() does return the key state at the instant that GetAsyncKeyState() was called. On the other hand, GetKeyState() returns the key state based on the history of queued messages.

After much testing, I seem to have figured it out. MSDN states about GetKeyState() :

The key status returned from this function changes as a thread reads key messages from its message queue.

GetAsyncKeyState() still works on key up/down messages (not physical key state) however, it just doesn't wait for the message to be read. So if a key event message is sent via SendInput(), it will still return incorrectly - in fact, it will be incorrect before GetKeyState() because it will be incorrect immediately after the call.

A simple test to demonstrate this functionality is here (VS2010 solution) or just the source here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!