一、方法
C/C++ 在 Linux 中没有现成的键盘检测函数,可以利用 <termio.h> 中的 struct termios 结构体来构造键盘检测函数。至于 struct termios 的具体解析,这里不展开介绍,下面给出构造的键盘检测代码。
二、代码
#include <termio.h>
#include <stdio.h>
int scanKeyboard()
{int in;struct termios new_settings;struct termios stored_settings;tcgetattr(0,&stored_settings);new_settings = stored_settings;new_settings.c_lflag &= (~ICANON);new_settings.c_cc[VTIME] = 0;tcgetattr(0,&stored_settings);new_settings.c_cc[VMIN] = 1;tcsetattr(0,TCSANOW,&new_settings);in = getchar();tcsetattr(0,TCSANOW,&stored_settings);return in;
}int main()
{while(1){int ascii = scanKeyboard();printf(":%d\n",ascii);if(ascii==27) break;}return 0;
}