linux下读取键盘扫描码

键盘扫描码有两种:  
一个是make   code,也就是键被按下和按住不放时产生  
另一种是break   code,在键被释放时产生。  
每个键都有自己唯一的make   code和break   code。  
提供一个我在Linux下的实现,就是使用ioctl   改变终端I/O模式。  
测试程序在“a”健被按下时退出。  
#include   <stdio.h>  
#include   <stdlib.h>  
#include   <termios.h>  
#include   <sys/ioctl.h>  
#include   <unistd.h>  
#include   <linux/kd.h>  
int main(void)  
{  
 struct   termios     oldtermios,newtermios;  
 int         oldmode;  
 unsigned   short   key;  
 int   i;  
 if((tcgetattr(fileno(stdin),&oldtermios))<0)  
 {  
  perror("tcgetaddr   error");  
  exit(1);  
 }  
 if((tcgetattr(fileno(stdin),&newtermios))<0)  
 {  
  perror("tcgetaddr   error");  
  exit(1);  
 }  
 newtermios.c_lflag   &=   ~(ICANON|ECHO|ISIG);  
 newtermios.c_iflag   =   0;  
 newtermios.c_cc[VMIN]   =   0;  
 newtermios.c_cc[VTIME]   =   1;   //=0延时0   ,=1延时1s
 if(tcsetattr(fileno(stdin),TCSAFLUSH,&newtermios))  
 {  
  perror("tcsetattr   error");  
  exit(1);  
 }  
 ioctl(fileno(stdin),KDGKBMODE,&oldmode);  
 if(ioctl(fileno(stdin),KDSKBMODE,K_RAW))  
 {  
  perror("ioctl   error");  
  exit(1);  
 }  
 while(1)  
 {  
  if(read(fileno(stdin),&key,sizeof(key))>0)  
   printf("   key   =   0x%x   /n",key);  
  if   (key   ==   0x1e)//key   a   down   ,   exit.  
   break;  
  key   =   0;  
 }  
 ioctl(fileno(stdin),KDSKBMODE,oldmode);  
 tcsetattr(fileno(stdin),TCSANOW,&oldtermios);  
 return   0;  
}  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值