What is the fastest way to determine a key press and key holding in Win32?

judeclarke picture judeclarke · Dec 27, 2011 · Viewed 30k times · Source

What is the fastest way to determine a key press and also how to determine if a key is being held? It appears that window messaging is slow. Please provide an example of how to do so, and why it is faster than an alternative.

To be clear, this for a real time loop (a simulation) so I am looking for the fastest way to determine if a key has been pressed and also to check to see if it is being held.

Answer

Bukes picture Bukes · Dec 27, 2011

GetAsyncKeyState() is what you're looking for. It reads the physical state of the keyboard, regardless of the input queue state. If the high-bit is set, then the key was down at the time of the call.

// Fetch tab key state.
SHORT tabKeyState = GetAsyncKeyState( VK_TAB );

// Test high bit - if set, key was down when GetAsyncKeyState was called.
if( ( 1 << 15 ) & tabKeyState )
{
    // TAB key down... 
}

Also, for the record, Windows is not a real-time operating system. If your application requires real-time precision, you may want to select another platform.