红联Linux门户
Linux帮助

Linux下利用X11获取鼠标的系统位置

发布时间:2016-12-30 15:30:16来源:linux网站作者:求是07
X11获取鼠标的位置。
 
#include <stdio.h>  
#include <X11/Xlib.h>  
char *key_name[] = {  
"left",  
"second (or middle)",  
"right",  
"pull_up",  
"pull_down"  
};  
int main(int argc, char **argv)  
{  
Display *display;  
XEvent xevent;  
Window window;  
if( (display = XOpenDisplay(NULL)) == NULL )  
return -1;  
window = DefaultRootWindow(display);  
XAllowEvents(display, AsyncBoth, CurrentTime);  
XGrabPointer(display,  
window,  
1,  
PointerMotionMask | ButtonPressMask | ButtonReleaseMask ,  
GrabModeAsync,  
GrabModeAsync,  
None,  
None,  
CurrentTime);  
while(1) {  
XNextEvent(display, &xevent);  
switch (xevent.type) {  
case MotionNotify:  
printf("Mouse move      : [%d, %d]\n", xevent.xmotion.x_root, xevent.xmotion.y_root);  
break;  
case ButtonPress:  
printf("Button pressed  : %s\n", key_name[xevent.xbutton.button - 1]);  
break;  
case ButtonRelease:  
printf("Button released : %s\n", key_name[xevent.xbutton.button - 1]);  
break;  
}  
}  
return 0;  
}
 
编译的时候注意使用
gcc 1.c -lX11 1 这样才能生成可执行文件。
随着鼠标移动会打印相关的信息。
 
这里说一下相关的函数。
XAllowEvents( *display,  event_mode,  time);
display Specifies the connection to the X server.
event_mode Specifies the event mode. You can pass AsyncPointer,SyncPointer,
AsyncKeyboard, SyncKeyboard, Replay-Pointer, ReplayKeyboard, AsyncBoth, or
SyncBoth.
time Specifies the time. You can pass either a timestamp or CurrentTime.
主要注意的是鼠标事件,和当前的时间,如果有兴趣可以获取特定的时间,用时间戳机制。
int XGrabPointer( *display,  grab_window,  owner_events,event_mask,keyboard_mode, confine_to,  cursor,  time);
主要获取Xserver鼠标的信息。
display Specifies the connection to the X server.
grab_window Specifies the grab window.
owner_events Specifies a Boolean value that indicates whether the
pointer events are to be reported as usual or reported with respect to the grab window 
if selected by the event mask.
event_mask Specifies which pointer events are reported to the client. 
The mask is the bitwise inclusive OR of the valid pointer event mask bits.
pointer_mode Specifies further processing of pointer events.
You can pass GrabModeSync or GrabModeAsync.keyboard_mode Specifies further 
processing of keyboard events. Youcan pass GrabModeSync or GrabModeAsync.
confine_to Specifies the window to confine the pointer in or None.
cursor Specifies the cursor that is to be displayed during the grab or None.
 
这个具体情况,需要看对应的参数才可以
这里可以使linux的命令 man
所有的库函数在linux都可以使用man
比如
man XGrabPointer
显示如下:
Linux下利用X11获取鼠标的系统位置
这里可以再一些编程中或许会用的到。尤其是利用在ubuntu下名的一些图形编程,X11是基于C/S架构的图形库。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/27388.html