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

18,181

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.

Share:
18,181
Osaid
Author by

Osaid

FPGA (Xilinx, Altera): Firmware development on (Xilinx ISE & Quartus II @ VERILOG), simulation (Modelsim) and testing (FPGA boards). Microcontroller: Firmware development (Keil & Mplab @ (C++/ASSEMBLY) ), simulation (Proteus) and testing (Hardware prototype).

Updated on June 04, 2022

Comments

  • Osaid
    Osaid about 2 years

    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.