C/C++ Keyboard Event Acquisition
Category Programming Techniques
In the Windows system's Visual Studio, you can use the _kbhit() function to acquire keyboard events. When using it, you need to include the conio.h header file. Example:
Example
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int ch;
while (1){
if (_kbhit()) { // If a key is pressed, the _kbhit() function returns true
ch = _getch(); // Use the _getch() function to get the key value
cout << ch;
if (ch == 27) { break; } // When the ESC key is pressed, break the loop, the key value of the ESC key is 27.
}
}
system("pause");
}
In Unix/Linux, the kbhit() function is not provided. We can implement the kbhit() program ourselves.
Example
#include <stdio.h>
#include <termios.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
void init_keyboard()
{
tcgetattr(0, &initial_settings);
new_settings = initial_settings;
new_settings.c_lflag |= ICANON;
new_settings.c_lflag |= ECHO;
new_settings.c_lflag |= ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
unsigned char ch;
int nread;
if (peek_character != -1) return 1;
new_settings.c_cc[VMIN] = 0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0, &ch, 1);
new_settings.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_settings);
if (nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if (peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0, &ch, 1);
return ch;
}
int main()
{
init_keyboard();
while (1)
{
kbhit();
printf("\n%d\n", readch());
}
close_keyboard();
return 0;
}
#
-
** TD
* 429**[email protected]
Keyboard Key Code Table
| Key Code Values (keyCode) for Alphabet and Number Keys | | Key | keyCode | Key | keyCode | Key | keyCode | Key | keyCode | | A | 65 | J | 74 | S | 83 | 1 | 49 | | B | 66 | K | 75 | T | 84 | 2 | 50 | | C | 67 | L | 76 | U | 85 | 3 | 51 | | D | 68 | M | 77 | V | 86 | 4 | 52 | | E | 69 | N | 78 | W | 87 | 5 | 53 | | F | 70 | O | 79 | X | 88 | 6 | 54 | | G | 71 | P | 80 | Y | 89 | 7 | 55 | | H | 72 | Q | 81 | Z | 90 | 8 | 56 | | I | 73 | R | 82 | 0 | 48 | 9 | 57 |
| Key Code Values (keyCode) for Numeric Keypad Keys | Key Code Values (keyCode) for Function Keys | | Key | keyCode | Key | keyCode | Key | keyCode | Key | keyCode | | 0 | 96 | 8 | 104 | F1 | 112 | F7 | 118 | | 1 | 97 | 9 | 105 | F2 | 113 | F8 | 119 | | 2 | 98 | * | 106 | F3 | 114 | F9 | 120 | |