Trying to make my own version of getch( ) that will work like <conio.h>'s getch( ) where a character can be removed from the keyboard buffer without having to wait for a newline/carriage return.
Here is what I've come up with so far. The code looks like it should work; however, the program does not seem to respond to any keyboard inputs:
Code:#include<iostream>
#include<cctype>
#include<string>
#include<windows.h>
using namespace std;
char getch();
int main()
{
do{
cout << "\nEnter something: ";
cout << getch();
cout << "\n\nWould ye' like to try again? (Y/N) ";
}while(toupper(getch())!='N');
return 0;
}
char getch()
{
HANDLE hIn;
INPUT_RECORD InRec;
DWORD EventCount, fdwSaveOldMode;
hIn = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hIn, &fdwSaveOldMode);
SetConsoleMode(hIn, ENABLE_ECHO_INPUT|ENABLE_LINE_INPUT);
for(;;)
{
GetNumberOfConsoleInputEvents(hIn, &EventCount);
if(EventCount)
{
ReadConsoleInput(hIn, &InRec, 1, NULL);
if(InRec.EventType == KEY_EVENT)
{
SetConsoleMode(hIn, fdwSaveOldMode);
return static_cast<signed char>(InRec.Event.KeyEvent.uChar.AsciiChar);
}
}
}
}
Additional info:
My usage of SetConsoleMode( ) is based on this MSDN excerpt:
Quote:
ENABLE_LINE_INPUT
0x0002 The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_ECHO_INPUT
0x0004 Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.