c++: function that returns current key input as any type

Previously, I used GetAsyncKeyState() from windows.h and ran a while (true) loop every case that press key.

But, it uses much CPU usage, even Sleep(50)->'0.05sec' every one loop.

If the Windows OS is already checking keys, do I have ways to get the key state from the OS? If I do that, will CPU usage be lower?

Anyway, please help me to know an easy way to get current key inputs.

For example, if the user is pressing A & B & Home at same time, the function that I imagine returns {'A','B','Home'} as any string or other type.

addition: The code that I write is like this.

if (getasynckeystate('A') != 0)
{
    IsA = true; //bool
}
else
{
    IsA = false; 
}
//skip......

It runs to all of key (Fnkey,num,word,etc...) It looks uneffective even to me.


Solution 1:

GetAsyncKeyState is the OS; therefore your question doesn't make much sense.

But the broader answer is that you should not be polling for keyboard states like this. Instead, you should be listening for when the OS tells your application that a key was pressed. This is via a message loop and handling WM_CHAR or WM_KEYDOWN, et al. This is how you solve the (perceived) performance problem. This way instead of your code running every N milliseconds, it runs only when the keyboard state changes.

Other advantages:

  • This will follow the behavior of keyboard focus. So when your application is not focused, it will not respond to keyboard events (which users would not expect)
  • Polling will fail to recognize very quick key presses if it lands between polls. WM_KEYDOWN will handle all keyboard presses with no jitter and no gaps.
  • GetAsyncKeyState gets the current keyboard state, which (maybe unintuitively) does not always match what the user expects. For example if the user hits a key at the moment your application freezes for a bit, users expect the key to still register. That's standard behavior and if you use GetAsyncKeyState, the keypress will be lost and the user will be forced to press it again. The experience is that users feel that your application is not reliable.

Another note about performance though: Calling GetAsyncKeyState every 50ms should not cause significant CPU usage. I suspect if there really is a performance issue, it's not been described in your question.