Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

When should I use one over the other?

like image 911
Markus Meskanen Avatar asked Jul 21 '13 09:07

Markus Meskanen


People also ask

What is GetAsyncKeyState?

The GetAsyncKeyState function works with mouse buttons. However, it checks on the state of the physical mouse buttons, not on the logical mouse buttons that the physical buttons are mapped to.

What does GetAsyncKeyState return?

GetAsyncKeyState returns a 16-bit signed value. The high bit is set when the current real-time state of the key indicates that it is being held down. The low bit is set when the key has transitioned from a released to a pressed state (like when the key is first pressed).


1 Answers

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

like image 58
Iosif Murariu Avatar answered Oct 03 '22 23:10

Iosif Murariu