Modern getch() implementation on Windows C/C++


In the DOS era, where 16-bit applications are dominant, the DOS compilers such as Turbo C, Borland Pascal provide many utilities/methods/functions related to keyboard and screen. To check a key is pressed is one of the favourites used frequently at that time. For example,

1
2
3
4
5
6
#include <conio.h>
 
int main {
    getch();
    return 0;
}
#include <conio.h>

int main {
    getch();
    return 0;
}

The getch() is declared in conio.h but in windows, there is no such header file! The below is the modern way (can be compiled under 32bit g++ or 64 bit) of detecting the key pressed in windows console (if there is any).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <windows.h>
 
using namespace std;
 
TCHAR getch() {
  DWORD mode, cc;
  HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
  if (h == NULL) {
        return 0; // console not found
  }
  GetConsoleMode( h, &mode );
  SetConsoleMode( h, mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT) );
  TCHAR c = 0;
  ReadConsole( h, &c, 1, &cc, NULL );
  SetConsoleMode( h, mode );
  return c;
}
 
int main() {
    TCHAR k;
    while ((k = getch()) != 'Z') {
        cout << "Key: " << k << " = " << (int)k << endl;
    }
    return 0;
}
#include <iostream>
#include <windows.h>

using namespace std;

TCHAR getch() {
  DWORD mode, cc;
  HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
  if (h == NULL) {
        return 0; // console not found
  }
  GetConsoleMode( h, &mode );
  SetConsoleMode( h, mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT) );
  TCHAR c = 0;
  ReadConsole( h, &c, 1, &cc, NULL );
  SetConsoleMode( h, mode );
  return c;
}

int main() {
    TCHAR k;
    while ((k = getch()) != 'Z') {
        cout << "Key: " << k << " = " << (int)k << endl;
    }
    return 0;
}

The above is compiled under g++/windows compiler (gcc 4.x) and the pre-compiled binary for windows can be downloaded [here] cnt Modern getch() implementation on Windows C/C++ 16 bit 32 bit 64 bit beginner c / c++ code code library console implementation programming languages .

The console application looks for key pressed and print the corresponding ASCII code. Press ‘Z’ (captial) to quit. However, it still fails to detect the functional keys, such as F1, Ctrl, Shift etc. The Enter (Return ASCII=13) and Backspace (ASCII=8) can be captured through.

getch Modern getch() implementation on Windows C/C++ 16 bit 32 bit 64 bit beginner c / c++ code code library console implementation programming languages

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
393 words
Last Post: Simple C++ Animation - Ultimate Color Randomness
Next Post: C++ Coding Exercise - Factor Utility on Windows

The Permanent URL is: Modern getch() implementation on Windows C/C++

Leave a Reply