我正在使用此代碼從linux中的dev/input/event *讀取鼠標事件。如何讀取Linux中的低級別鼠標點擊位置。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <fcntl.h>
#define MOUSEFILE "/dev/input/event4"
int main()
{
int fd;
struct input_event ie;
if((fd = open(MOUSEFILE, O_RDONLY)) == -1) {
perror("opening device");
exit(EXIT_FAILURE);
}
while(read(fd, &ie, sizeof(struct input_event))) {
printf("time %ld.%06ld\ttype %d\tcode %d\tvalue %d\n",
ie.time.tv_sec, ie.time.tv_usec, ie.type, ie.code, ie.value);
}
return 0;
}
這使我的格式的結果:
時間1342517261.840285 2型的代碼0值-1
'時間' 是時間戳,它返回時的時間事件發生了。
'code'是事件代碼,例如REL_X或KEY_BACKSPACE,完成 列表位於include/linux/input.h中。
「值」是事件攜帶的值。對於 版本,對於 EV_REL,EV_ABS(操縱桿...)的絕對新值或EV_KEY的0的相對變化,對於按鍵按壓1和對於自動重複2的相對變化。
當我點擊,我得到的事件,但我沒有得到在屏幕上的鼠標的位置,是什麼方式獲得在屏幕上的鼠標的位置。
編輯1:那麼作爲事實證明,我必須使用相對座標,以獲得鼠標座標。我相信這是一個共同的要求,從而有可能是庫/預先存在可以用來獲得座標的代碼。關於這個主題的任何信息都會非常有用。
EDIT2:SOLUTION
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <fcntl.h>
#include <X11/Xlib.h>
#define MOUSEFILE "/dev/input/event4"
int main()
{
int fd;
struct input_event ie;
Display *dpy;
Window root, child;
int rootX, rootY, winX, winY;
unsigned int mask;
dpy = XOpenDisplay(NULL);
XQueryPointer(dpy,DefaultRootWindow(dpy),&root,&child,
&rootX,&rootY,&winX,&winY,&mask);
if((fd = open(MOUSEFILE, O_RDONLY)) == -1) {
perror("opening device");
exit(EXIT_FAILURE);
}
while(read(fd, &ie, sizeof(struct input_event))) {
if (ie.type == 2) {
if (ie.code == 0) {
XQueryPointer(dpy,DefaultRootWindow(dpy),&root,&child,
&rootX,&rootY,&winX,&winY,&mask);
//rootX += ie.value;
}
else if (ie.code == 1) {
XQueryPointer(dpy,DefaultRootWindow(dpy),&root,&child,
&rootX,&rootY,&winX,&winY,&mask);
// rootY += ie.value;
}
printf("time%ld.%06ld\tx %d\ty %d\n",
ie.time.tv_sec, ie.time.tv_usec, rootX, rootY);
} else
printf("time %ld.%06ld\ttype %d\tcode %d\tvalue %d\n",
ie.time.tv_sec, ie.time.tv_usec, ie.type, ie.code, ie.value);
}
return 0;
}
XQueryPointer似乎更方便的解決方案。感謝@perreal的指導。
嗨,該代碼看起來非常優雅.Thanks。但它給了我以下錯誤:1。未定義的XOpenDisplay引用,2.未定義的XQueryPointer引用。 – rajat 2012-07-17 11:39:21
您需要使用X11 lib進行編譯:'gcc main.c -lX11'。 – perreal 2012-07-17 11:45:01
是的,它的工作:)。但是座標是混亂的,0,0點是在屏幕之間的某處。 – rajat 2012-07-17 12:14:42