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

Markus Meskanen picture Markus Meskanen · Jul 21, 2013 · Viewed 15.7k times · Source

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

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

When should I use one over the other?

Answer

Iosif Murariu picture Iosif Murariu · Jul 21, 2013

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).