The getch function is available in the winbgim implementation of BGI
graphics. You do not need to include conio.h; just include graphics.h.
The function reads one character from the keyboard and returns its ASCII
value (without waiting for a return key). In order to work, the user must
click in the graphics window (i.e., the Windows focus must be in the
graphics window). For special keys, the getch function first returns
ASCII 0. The next call will then return one of these special keys:
#define KEY_HOME 71
#define KEY_UP 72
#define KEY_PGUP 73
#define KEY_LEFT 75
#define KEY_CENTER 76
#define KEY_RIGHT77
#define KEY_END 79
#define KEY_DOWN 80
#define KEY_PGDN 81
#define KEY_INSERT 82
#define KEY_DELETE 83
#define KEY_F1 59
#define KEY_F2 60
#define KEY_F3 61
#define KEY_F4 62
#define KEY_F5 63
#define KEY_F6 64
#define KEY_F7 65
#define KEY_F8 66
#define KEY_F9 67
#include "graphics.h"
#include <stdio.h>// Provides sprintf
#include <iostream.h> // Provides cout
void outintxy(int x, int y, int value);
int main( )
{
int i;
char c;
// Initialize the graphics window.
initwindow(400, 300);
// Convert some numbers to strings and draw them in graphics window:
outtextxy(10, 10, "Here are some numbers:");
for (i = 10; i <= 100; i += 10)
outintxy(20, i+10, i);
// Get some characters from the keyboard until an X is typed:
outtextxy(20, 130, "Click in this graphics window,");
outtextxy(20, 140, "and then press arrow keys.");
outtextxy(20, 150, "Watch the console window while pressing.");
outtextxy(20, 160, "Press X to exit.");
do
{
c = (char) getch( );
if (c != 0)
cout << "That is ASCII value: " << (int) c << endl;
else
{ // Process one of the special keys:
c = (char) getch( );
switch (c)
{
case KEY_HOME: cout << "Home key." << endl; break;
case KEY_UP:cout << "Up key." << endl; break;
case KEY_PGUP: cout << "PgUp key." << endl; break;
case KEY_LEFT: cout << "Left key." << endl; break;
case KEY_CENTER: cout << "Center key." << endl; break;
case KEY_RIGHT: cout << "Right key." << endl; break;
case KEY_END: cout << "End key." << endl; break;
case KEY_DOWN: cout << "Down key." << endl; break;
case KEY_PGDN: cout << "PgDn key." << endl; break;
case KEY_INSERT: cout << "Insert key." << endl; break;
case KEY_DELETE: cout << "Delete key." << endl; break;
case KEY_F1:cout << "F1 key." << endl; break;
case KEY_F2:cout << "F2 key." << endl; break;
case KEY_F3:cout << "F3 key." << endl; break;
case KEY_F4:cout << "F4 key." << endl; break;
case KEY_F5:cout << "F5 key." << endl; break;
case KEY_F6:cout << "F6 key." << endl; break;
case KEY_F7:cout << "F7 key." << endl; break;
case KEY_F8:cout << "F8 key." << endl; break;
case KEY_F9:cout << "F9 key." << endl; break;
default: cout << "Unknown extended key." << endl;
}
}
} while ((c != 'x') && (c != 'X'));
closegraph( );
}
void outintxy(int x, int y, int value)
{
char digit_string[20];
sprintf(digit_string, "%d", value);
outtextxy(x, y, digit_string);
}