- 论坛徽章:
- 0
|
本帖最后由 lc-soft 于 2012-09-13 20:21 编辑
先看代码:
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/ioctl.h>
- #include <linux/input.h>
- #include <fcntl.h>
- #include <termios.h>
- static struct termios tm;
- static int fd = STDIN_FILENO;
- int Set_Raw(int t)
- {
- if (t > 0) {
- if(tcgetattr(fd, &tm) < 0) {
- return -1;
- }
- /* 设置终端为无回显无缓冲模式 */
- tm.c_lflag &= ~(ICANON|ECHO);
- tm.c_cc[VMIN] = 1;
- tm.c_cc[VTIME] = 0;
- if(tcsetattr(fd, TCSANOW, &tm) < 0) {
- return -1;
- }
- printf("\033[?25l");/* 隐藏光标 */
- } else {
- tm.c_lflag |= ICANON;
- tm.c_lflag |= ECHO;
- tm.c_cc[VMIN] = 1;
- tm.c_cc[VTIME] = 0;
- if(tcsetattr(fd,TCSANOW,&tm)<0) {
- return -1;
- }
- printf("\033[?25h"); /* 显示光标 */
- }
- return 0;
- }
- int main(int argc, char *argv[])
- {
- int fd;
- struct input_event event;
-
- Set_Raw(1);
- if( (fd = open("/dev/input/event3", O_RDONLY)) == -1) {
- printf("error: open keyboard: %s\n",strerror(errno));
- exit(-1);
- }
-
- while(1){
- if(read(fd, &event, sizeof(event)) < 0){
- printf("error\n");
- return -1;
- } else {
- if(event.type == EV_KEY) {
- printf("%d, ", event.code);
- switch(event.value)
- {
- case 0: printf("free!\n");break; /* 释放 */
- case 1: printf("press!\n");break; /* 按下 */
- case 2: printf("pressing!\n");break; /* 按住 */
- }
- }
- }
- }
- return 0;
- }
复制代码 在其它平台上测试,不是/dev/input/event3而是/dev/input/event0;
而且,按住某个键时,显示的结果不是pressing!,而是free!和press!成对显示。
前者倒没什么大碍,可后者,无法获取按键的“按住”状态,对于按键控制的程序,比如:靠长按按键实现某些动作的小游戏,有点不适。
不知有没有更好的解决方法。
|
|