• Articles
  • An alternate to using getch()
Published by
Feb 22, 2010 (last update: Feb 24, 2010)

An alternate to using getch()

Score: 3.2/5 (65 votes)
*****
OK, I have seen enough people suggesting the use of non-standard getch() or _getch().

Please, refrain from using the conio.h library as it is unreliable and non-standard. The conio.h of MSV C++ 08 differs hugely from the one in Mingw C.
Lots of functions in there like textcolor(), cprintf, etc., are deprecated and there are other alternatives to it.

Here, I shall post one such alternative to getch() which works using Win API.
Oh, it will only work on windows....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <windows.h>
CHAR GetCh (VOID)
{
  HANDLE hStdin = GetStdHandle (STD_INPUT_HANDLE);
  INPUT_RECORD irInputRecord;
  DWORD dwEventsRead;
  CHAR cChar;

  while(ReadConsoleInputA (hStdin, &irInputRecord, 1, &dwEventsRead)) /* Read key press */
    if (irInputRecord.EventType == KEY_EVENT
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_SHIFT
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_MENU
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_CONTROL)
    {
      cChar = irInputRecord.Event.KeyEvent.uChar.AsciiChar;
	ReadConsoleInputA (hStdin, &irInputRecord , 1, &dwEventsRead); /* Read key release */
	return cChar;
    }
  return EOF;
}

The above code should work as it worked for me.

Suggestions and improvements are accepted. I am a tyro in this field.