键盘扫描码有两种:
一个是make code,也就是键被按下和按住不放时产生
另一种是break code,在键被释放时产生。
每个键都有自己唯一的make code和break code。
提供一个我在Linux下的实现,就是使用ioctl 改变终端I/O模式。
测试程序在“a”健被按下时退出。
#include
#include
#include
#include
#include
#include
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;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ma100/archive/2007/02/07/1504270.aspx
以上代码,我在suse liux下,没有成功。原因是 if(ioctl(fileno(stdin),KDSKBMODE,K_RAW)) 没有成功。
参考下面文章:http://www.linuxjournal.com/article/2783,需要弄清楚ioctl对键盘的操作。