XSelectInput is not working for ButtonPressEvents,how to do it?

你。 提交于 2019-12-07 18:12:33

问题


I am writing a simple programmes in C where i want to capture all the mouse and Keyboard events that are taking place. I tried to use "XGrabPointer" but it results in locking the screen and i can not go to other applications. I tried with "XSelectInput()" and now i am receiving the keyboard events successfully but i am not getting any mouse click events.

Any idea how can i do it?

The code snippet is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>

int main(int argc, char **argv)
{
   Display *dpy;
   Window root;
  unsigned long event_mask;
    event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask | ButtonPressMask  | ButtonReleaseMask;
    if((dpy = XOpenDisplay(NULL)) == NULL) {
        perror(argv[0]);
        exit(1);
    }
dpy = XOpenDisplay(NULL);
root = XDefaultRootWindow(dpy);

int state;
XWindowAttributes attributes;

XGetInputFocus(dpy,&root,&state);
printf("window id = %d\n"); 
XSelectInput(dpy,root,event_mask);


XEvent ev;
   while(1) {


      XNextEvent(dpy, &ev);
    if(ev.type==ButtonRelease){
    printf("button release\n");
    }

      if (ev.type== KeyPress) {
    printf("keypress event\n");
      }


  }

 return 0;

}

回答1:


As you're using the root window, there's probably something else getting the event, to make sure you get all events you will need to grab the mouse but nothing else will get the events so you need a way to exit like the q key in this example:

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>

int main(int argc, char **argv)
{
    Display *dpy;
    Window root;
    unsigned long event_mask;
    event_mask = KeyReleaseMask | ButtonReleaseMask;
    if((dpy = XOpenDisplay(NULL)) == NULL) {
        perror(argv[0]);
        exit(1);
    }
    dpy = XOpenDisplay(NULL);
    root = XDefaultRootWindow(dpy);

    XGrabPointer(dpy, root, False, ButtonReleaseMask, GrabModeAsync, 
         GrabModeAsync, None, None, CurrentTime);

    int state;
    XWindowAttributes attributes;

    XGetInputFocus(dpy,&root,&state);
    printf("window id = %d\n"); 
    XSelectInput(dpy,root,event_mask);


    XEvent ev;
    while(1) {


    XNextEvent(dpy, &ev);
    printf("Type: %d\n", ev.type);

    if(ev.type==ButtonRelease){
        printf("button release\n");
    }

    if (ev.type== KeyRelease) {
        printf("keypress event\n");
        if (XLookupKeysym(&ev.xkey, 0) == XK_q) {
        exit(0);
        }

    }


    }

    return 0;

}


来源:https://stackoverflow.com/questions/16977872/xselectinput-is-not-working-for-buttonpressevents-how-to-do-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!