Linux下C++/C终端获取键盘事件/termios结构详细解释

需求为能够直接获取键盘时间,对待输入不需要点击回车就能够直接相应。

类似于使用键盘进行拳皇等小游戏时的操作,可以直接在终端输入键盘指令就能够得到响应。
通常我们使用的终端输入方式cin需要点击回车后才能完成本次输入。因此cin并不能满足本次的要求
在Linux下可以通过termio进行键盘时间的获取,并且屏蔽掉回车键。如果需要查询某一个键的key数值,可以直接按键尝试,但遗憾的是不支持上下左右键。

在这里插入图片描述

#include <termio.h>
#include <stdio.h>
#include <unistd.h>
int scanKeyboard()
{
  //  struct termios
  //    {
  //      tcflag_t c_iflag;		/* input mode flags */
  //      tcflag_t c_oflag;		/* output mode flags */
  //      tcflag_t c_cflag;		/* control mode flags */
  //      tcflag_t c_lflag;		/* local mode flags */
  //      cc_t c_line;			/* line discipline */
  //      cc_t c_cc[NCCS];		/* control characters */
  //      speed_t c_ispeed;		/* input speed */
  //      speed_t c_ospeed;		/* output speed */
  //  #define _HAVE_STRUCT_TERMIOS_C_ISPEED 1
  //  #define _HAVE_STRUCT_TERMIOS_C_OSPEED 1
  //    };
  int in;
  struct termios new_settings;
  struct termios stored_settings;
  tcgetattr(STDIN_FILENO,&stored_settings); //获得stdin 输入
  new_settings = stored_settings;           //
  new_settings.c_lflag &= (~ICANON);        //
  new_settings.c_cc[VTIME] = 0;
  tcgetattr(STDIN_FILENO,&stored_settings); //获得stdin 输入
  new_settings.c_cc[VMIN] = 1;
  tcsetattr(STDIN_FILENO,TCSANOW,&new_settings); //

  in = getchar();

  tcsetattr(STDIN_FILENO,TCSANOW,&stored_settings);
  return in;
}



int main(int argc, char *argv[]) {

  while(1){
    printf(":%d\r\n",scanKeyboard());
    //    int input_id = scanKeyboard();
    //    switch(input_id) {
    //      case 119:  //w or can set as case 'w':
    //      case 87:   //W case 'W':
    //        break;
    //      case 115: //s
    //      case 83:  //S
    //        break;
    //      case 97:  //a
    //      case 67:  //A
    //        break;
    //      case 100: //d
    //      case 68:  //D
    //        break;
    //      default:
    //        break;
    //    }
  }
}

参考:
https://www.runoob.com/w3cnote/c-get-keycode.html
https://blog.youkuaiyun.com/u013467442/article/details/51173441

linux termios结构详细解释

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值