linux下利用X11获取鼠标的系统位置。
#include
#include
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 orCurrentTime.
主要注意的是鼠标事件,和当前的时间,如果有兴趣可以获取特定的时间,用时间戳机
制。
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 reportedwith respect to the grab window
if selected by theevent mask.
event_mask Specifies which pointer events are reported to theclient.
The mask is the bitwise inclusive OR of the valid pointer event mask bits.
pointer_mode Specifies further processing of pointer events.
Youcan 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 orNone.
cursor Specifies the cursor that is to be displayed during thegrab or None.
这个具体情况,需要看对应的参数才可以
这里可以使linux的命令 man
所有的库函数在linux都可以使用man
比如
manXGrabPointer
显示如下
这里可以再一些编程中或许会用的到。尤其是利用在ubuntu下名的一些图形编程,X11是基于C/S架构的图形库。欢迎交流,欢迎留言。