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…
- ClearInputBuffer – Clears key events from input buffer using _kbhit
- Pause – Much like window’s ‘Pause’ command, except for the animation of ellipses.
#include
#include
void ClearInputBuffer()
{
while( _kbhit() )
{
// Read and ignore chars from input buffer resulting in removal from input buffer
_getch();
}
}
void Pause( const char* Msg = NULL )
{
std::cout << ( Msg ? Msg : "Press a key to continue" );
const int EllipsesCount = 3;
const char* MoveBackChars[EllipsesCount] = { "\b", "\b\b", "\b\b\b" };
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]