GetKeyState() vs. GetAsyncKeyState() vs. getch()?

烈酒焚心 提交于 2019-12-20 18:04:38

问题


What's the difference between getting a key press with:

  • GetKeyState()
  • GetAsyncKeyState()
  • getch()?

When should I use one over the other?


回答1:


GetKeyState() and GetAsyncKeyState() are Windows specific APIs, while getch() works on other non-Windows-specific C compilers.

GetKeyState() gets the key status returned from the thread's message queue. The status does not reflect the interrupt-level state associated with the hardware.

GetAsyncKeyState() specifies whether the key was pressed since the last call to GetAsyncKeyState(), and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState().

What I've seen in practice is that if you hold a key pressed and assign a behavior when the key is pressed, if you use GetKeyState(), the behavior will be called more times than if you'd have used GetAsyncKeyState().

In games, I prefer using GetAsyncKeyState().

(You can also check for more details on the MSDN blog).




回答2:


Think what async means.

  • GetAsyncKeyState() gets the key state asynchronously, i.e., without waiting for anything, i.e. NOW.

  • GetKeyState() gets the key state synchronously, it is the key state of the key that you are about to read with getch(). It is queued in the keyboard buffer along with the keypresses themselves.

As an example, imagine the following has been typed, but hasn't yet been read:

  • h
  • i
  • shift+1
  • ctrl(held down)

GetAsyncKeyState() will return ctrl pressed

GetKeyState() will returnH presseduntil you callgetch()`

GetKeyState() will then return I pressed until you call getch()

GetKeyState() will then return shift pressed, 1 pressed until you call getch(), which will return ! (result from pressing shift+1)

GetKeyState() will then return ctrl pressed



来源:https://stackoverflow.com/questions/17770753/getkeystate-vs-getasynckeystate-vs-getch

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