How can I detect if any key is pressed by the user in C++ (console)?

孤街浪徒 提交于 2019-12-11 04:09:32

问题


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 )



来源:https://stackoverflow.com/questions/13217212/how-can-i-detect-if-any-key-is-pressed-by-the-user-in-c-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!