-->

How can I detect if any key is pressed by the user

2019-07-11 07:06发布

问题:

I am writing a C++ CLI application how can I detect if any key is pressed by the user. I've seen that in c# but how can it be implement in c++

while(1)
     {
      while(/* code to check if any key is pressed*/)
           {        //rest of the code
                    // sleep function
           }
     }

Hint: like in CLI games to move or to take certain action when a key is pressed or don't do any thing if no input is given.

回答1:

On windows at least you could use GetKeyState



回答2:

we can use _kbhit() function in c++. _kbhit is equal to 1 if any key is pressed. You have to clear the _kbhit buffer else it will remain 1. Method for clearing is character = getch(); This will save the last entered key in character which you can compare and decide which action to perform on which key.



回答3:

While loop can be CPU consuming, i do not advice busy waiting method, instead you should think of event hooking.

Here you can read about winapi keystroke event hooking C++ Win32 keyboard events

If you are still interested to use the while loop, you should also free some resources by sleeping after checking that a condition is false (e.g. nanosleep )