键盘扫描码有两种:
一个是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;
}
一个是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;
}