網上找了很多方法,都比較雜亂。這篇文章專注于讀取鼠標的動作:左鍵、右鍵、中鍵、滾輪。
linux的設備都以文件形式存放,要讀取鼠標,有兩種方法,一種是通過/dev/input/mice,一種是通過/dev/input/eventx (x是標號,0,1,2..... 具體的進這個文件夾查看)。兩種方式各有優劣,后面講。
我們先從簡單的開始 讀取/dev/input/mice獲取鼠標事件。
?一般的Linux系統無論鼠標是否連接,mice文件都會存在。讀取操作非常簡單
讀取流程:
1.使用open()函數打開該文件
2.read函數讀取該文件
3.在while循環中輪詢并打印事件
下面看看代碼:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>int main(int argc, char** argv)
{int fd, bytes;char data[3];const char *pDevice = "/dev/input/mice";// Open Mousefd = open(pDevice, O_RDWR);if(fd == -1){printf("ERROR Opening %s\n", pDevice);return -1;}int left, middle, right;signed char x, y;while(1){// Read Mouse bytes = read(fd, data, sizeof(data));if(bytes > 0){left = data[0] & 0x1; right = data[0] & 0x2;middle = data[0] & 0x4;x = data[1];y = data[2];printf("x=%d, y=%d, left=%d, middle=%d, right=%d\n", x, y, left, middle, right);} }return 0;
}
從mice文件中讀取三個字節數據,data[0]內含按鍵信息,最低位為1時代表左鍵按下即xxxx xxx1時左鍵按下。以此類推,最后三位分別代表左鍵、右鍵、中鍵。?data[1]、data[2]代表x與y的相對坐標,即本次鼠標移動與上次鼠標移動了多少坐標,向左則x為負,向下則y為負。
到這里通過mice文件獲取鼠標事件就已經結束了,肯定有人會問,滾輪呢?
讀取mice文件很簡單,但它的缺點就是不包含滾輪信息。
使用event文件獲取鼠標事件。
首先使用
sudo cat /dev/input/eventx
然后移動鼠標,如果出現輸出則可以確定鼠標對應的event文件
我的設備對應event6
在linux/input.h文件內定義了輸入事件結構體,根據該結構體來獲取信息
輸入事件的結構體:
struct input_event {struct timeval time;? //按鍵時間__u16 type;? //事件的類型__u16 code;? //要模擬成什么按鍵__s32 value;? //是按下1還是釋放0};
type:事件的類型
EV_KEY, 按鍵事件)鼠標的左鍵右鍵等;
EV_REL, 相對坐標
EV_ABS, 絕對坐標
code 事件代碼
主要是一些宏定義,具體可查看input.h內文件,如何使用請參考下面的代碼
value:事件的值
如果事件的類型代碼是EV_KEY,當按鍵按下時值為1,松開時值為0;如果事件的類型代碼是EV_ REL,value的正數值和負數值分別代表兩個不同方向的值。例如:如果code是REL_X,value是10的話,就表示鼠標相對于上一次的坐標,往x軸向右移動10個像素點。
代碼如下:
#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include <linux/input.h>int main(int argc, char** argv){int fd, bytes;struct input_event event;char data[3];const char *pDevice = "/dev/input/event6";// Open Mousefd = open(pDevice, O_RDWR);if(fd == -1){printf("ERROR Opening %s\n", pDevice);return -1;}while(1){// Read Mouse bytes = read(fd, &event, sizeof(struct input_event));if(event.type == EV_KEY){switch(event.code){case BTN_LEFT: printf("left:%d\n", event.value);break;case BTN_RIGHT: printf("right:%d\n",event.value);break;case BTN_MIDDLE: printf("middle:%d\n",event.value);break;}}if(event.type == EV_ABS){switch(event.code){case ABS_X: printf("x:%d\n",event.value);break; case ABS_Y: printf("y:%d\n",event.value);break; }}if(event.type == EV_REL){switch(event.code){ case REL_WHEEL: printf("wheel:%d\n", event.value);break; //滾輪}}}return 0; }
這里我的鼠標不支持讀取相對坐標,因此鼠標只讀取絕對坐標,注意滾輪事件屬于相對事件。
參考:linux - How do you read the mouse button state from /dev/input/mice? - Stack Overflow