设置为异步读取键盘代码与还原示例:
struct termios term_settings;
// Force terminal input to read keyboard input asynchronously
SetKeyboardNonblocking(&term_settings);
// TO:DO Your are code here.
// Not restoring the keyboard settings causes the input from the terminal to not work right
RestoreKeyboardBlocking(&term_settings);
1、设置控制台读取为异步
void SetKeyboardNonblocking(struct termios* initial_settings) {
struct termios new_settings;
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] = 0;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
2、欢迎控制台读取为?(若保存为同步则为同步)
void RestoreKeyboardBlocking(struct termios* initial_settings) {
tcsetattr(0, TCSANOW, initial_settings);
}
3、判定键代码为上下左右,CTRL+C,需要设置为异步读入键代码模式
返回控制代码:
1、上
2、下
3、左
4、右
5、CTRL+C
static int
ReadConsoleControlKey() {
static int key_list[3];
static int key_index = 0;
int& key_code = key_list[key_index];
key_code = getchar();
if (key_code <= 0) {
return 0;
}
if (key_index <= 0) {
if (key_code == 27) {
key_index++;
}
else {
key_index = 0;
if (key_code == 3) {
return 5;
}
}
}
else if (key_index <= 1) {
if (key_code == 91) {
key_index++;
}
else {
key_index = 0;
}
}
else if (key_index <= 2) {
key_index = 0;
switch (key_code)
{
case 65:
return 1;
case 66:
return 2;
case 67:
return 3;
case 68:
return 4;
}
}
return 0;
}