linux 處理鍵盤 滑鼠事件
阿新 • • 發佈:2019-02-05
1.讀取鍵盤的值,進行相應的處理。
#include <stdio.h> #include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int fd_kb; struct input_event event_kb; fd_kb = open("/dev/input/event1", O_RDONLY); //鍵盤輸入 if(fd_kb <= 0) { printf("open device error\n"); return 0; } while(1) { if(read(fd_kb, &event_kb, sizeof(event_kb)) == sizeof(event_kb)) { if (event_kb.type == EV_KEY) { //if (event_kb.value == 0 || event_kb.value == 1)//1表示按下,0表示釋放,會檢測到兩次 if (event_kb.value == 1)//鍵按下 { //printf("key %d %s\n", event_kb.code, (event_kb.value) ? "Pressed" : "Released"); if(event_kb.code == KEY_ESC) break; if(event_kb.code == KEY_Q) printf("q\n"); if(event_kb.code == KEY_W) printf("w\n"); if(event_kb.code == KEY_E) printf("e\n"); if(event_kb.code == KEY_R) printf("r\n"); } } } } close(fd_kb); return 0; }
2.獲取並處理滑鼠左鍵按下,右鍵按下,滾輪按下,滾輪上下滑動事件
#include <stdio.h> #include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int fd_mouse; struct input_event event_mouse; fd_mouse = open("/dev/input/event4", O_RDONLY); //滑鼠輸入 if(fd_mouse <= 0) { printf("open device error\n"); return 0; } while(1) { if(read(fd_mouse, &event_mouse, sizeof(event_mouse)) == sizeof(event_mouse)) { if(event_mouse.type = EV_REL) { if(event_mouse.code == REL_WHEEL) printf("REL_WHEEL %d\n", event_mouse.value);//-1表示下滑,1表示上滑 } if(event_mouse.code == BTN_LEFT && event_mouse.value==1)//左鍵按下,1表示按下,0表示釋放。不然會檢測到兩次 printf("left down: %d\n", event_mouse.code); if(event_mouse.code == BTN_RIGHT && event_mouse.value==1) printf("right down: %d\n", event_mouse.code); if(event_mouse.code == BTN_MIDDLE && event_mouse.value==1) printf("middle down: %d\n", event_mouse.code); } } close(fd_mouse); return 0; }
重要的參考資料:
1.http://staratsky.iteye.com/blog/1734631
2.http://blog.chinaunix.net/uid-20666855-id-4905405.html
3.http://blog.csdn.net/shijian408/article/details/26578007