How to check for keyhit in a windows console application?

For this purpose we use _kbhit function included in conio.h file. Please note that conio.h is a non-standard header file so can’t say if _kbhit will be available in other libraries. The purpose of  _kbhit is to check whether a key has been hit and so then we can use this function to wait till a key is pressed. To know which key is pressed we can use _getch or _getche functions immediately after a call to _kbhit. _kbhit returns TRUE if a key is pressed else returns FALSE.

Internally _kbhit used PeekConsoleInput windows console API to check whethere is a KEY_EVENT in input queue. If there is one then it returns TRUE. Note that _kbhit peeks on all events from input queue to check whether there is a KEY_EVENT. Note that extended keys are ignored!

Here are some functions to demonstrate the power of _kbhit

  1. ClearInputBuffer – Clears key events from input buffer using _kbhit
  2. Pause – Much like window’s ‘Pause’ command, except for the animation of ellipses.

[sourcecode language=’cpp’]#include

void ClearInputBuffer()
   while( _kbhit() )
      // Read and ignore chars from input buffer resulting in removal from input buffer

void Pause( const char* Msg = NULL )
   std::cout << ( Msg ? Msg : "Press a key to continue" );    const int EllipsesCount = 3;    const char* MoveBackChars[EllipsesCount] = { "b", "bb", "bbb" };    const char* AllClearText[EllipsesCount] = { " ", "  ", "   " };    const char* Ellipses[EllipsesCount] = { ".", "..", "..." };    int ActiveEllipsesIndex = 0;    while( true )// Animate until a key is pressed    {       std::cout << Ellipses[ActiveEllipsesIndex];       Sleep( 500 );       if( !_kbhit() )       {          std::cout << MoveBackChars[ActiveEllipsesIndex];          std::cout << AllClearText[ActiveEllipsesIndex];          std::cout << MoveBackChars[ActiveEllipsesIndex];       }       else       {          _getch();          break;       }       ActiveEllipsesIndex = (ActiveEllipsesIndex + 1) % EllipsesCount;    } } int main( void ) {    ClearInputBuffer();    Pause();    return 0; }[/sourcecode]

One thought on “How to check for keyhit in a windows console application?

  1. Nice piece of code, but I found a couple of minor issue.
    The code should have #include as the Sleep function is not defined and after each std::cout there should be a std::cout.flush(); to clear the output buffer. My compiler it was not outputting anything until the buffer filled up.

Appreciate your comments...