Mood:

Topic: VC++
Ever wondered how to implement getch and getche in Windows console application...
Here is how we do this...
int getch()
{
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
if( hStdIn == INVALID_HANDLE_VALUE )
{
return 0;
}// End if
DWORD dwInputMode = 0;
GetConsoleMode( hStdIn, &dwInputMode );
// Code that disables line input and echoing of entered character
SetConsoleMode( hStdIn, dwInputMode & ~ENABLE_LINE_INPUT &
~ENABLE_ECHO_INPUT );
char cBuff = 0;
DWORD dwBytesRead = 0;
if( !ReadFile( hStdIn, &cBuff, sizeof( cBuff ), &dwBytesRead, 0 ))
{
return 0;
}
// Return to previous settings
SetConsoleMode( hStdIn, dwInputMode );
return cBuff;
}// End getch
int getche()
{
HANDLE hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if( hStdOut != INVALID_HANDLE_VALUE )
{
char cGetCh = getch();
DWORD dwBytesWritten = 0;
WriteFile( hStdOut, &cGetCh, sizeof( cGetCh ), &dwBytesWritten, NULL );
return cGetCh;
}// End if
return 0;
}// End getche