2

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.

Osaid
  • 557
  • 1
  • 8
  • 23
  • I've found that we can also use _khbit() function in c++. _khbit is equal to 1 if any key is pressed. You have to clear the _khbit 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. – Osaid Nov 06 '12 at 09:00

3 Answers3

1

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.

udit043
  • 1,610
  • 3
  • 22
  • 40
Osaid
  • 557
  • 1
  • 8
  • 23
0

On windows at least you could use GetKeyState

Mihai Sebea
  • 398
  • 2
  • 10
-1

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 )

Community
  • 1
  • 1
Michael
  • 2,827
  • 4
  • 30
  • 47