Linux下捕捉键盘事件
直接上代码:
#include <termio.h> #include <stdio.h>
#include <unistd.h>
#include <fcntl.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 KeyTest() { return scanKeyboard(); } // 这个函数是跨平台的 int KeyTestNew() { #ifdef _WIN32 HANDLE keyboard = GetStdHandle(STD_INPUT_HANDLE); DWORD dw, num; if (!::GetNumberOfConsoleInputEvents(keyboard, &num) || num == 0) { return 0; } for (int i = 0; i < (int)num; ++i) { INPUT_RECORD input; ::ReadConsoleInputA(keyboard, &input, 1, (LPDWORD)(&dw)); if (input.EventType == KEY_EVENT && !input.Event.KeyEvent.bKeyDown) { //return (int)(input.Event.KeyEvent.uChar.AsciiChar); return (int)(input.Event.KeyEvent.wVirtualKeyCode); } } return 0; #endif #ifdef __linux__ struct termios oldt, newt; int c, oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); c = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (EOF != c) { if (c >= 'a' && c <= 'z') { return (c - 'a' + 'A'); } else { return c; } } else { return 0; } #endif } int main() { while(1) { int nNum = KeyTest(); printf("nNum:%d\n",nNum); } return 0; }