getting mouseclick coordinates with Xlib

前端 未结 3 1851
时光取名叫无心
时光取名叫无心 2020-12-19 20:39

I would like to know how to get the x and y coordinates of a mouseclick with Xlib anywhere on the screen. I\'ve found this post which gets the current pointer position

3条回答
  •  误落风尘
    2020-12-19 21:11

    You'll probably need to grab the pointer.

    I don't know if you want just want button presses of releases. I've changed it to presses, but you can pick up both with:

    XSelectInput(display, root, ButtonPressMask|ButtonReleaseMask) ;
    

    and add the ButtonRelease case back in.

    #include 
    #include 
    #include 
    #include 
    
    int main (){
        int x=-1,y=-1;
        XEvent event;
        int button;
        Display *display = XOpenDisplay(NULL);
        if (display == NULL) {
        fprintf(stderr, "Cannot connect to X server!\n");
        exit (EXIT_FAILURE);
        }
        Window root= XDefaultRootWindow(display);
        XGrabPointer(display, root, False, ButtonPressMask, GrabModeAsync,
             GrabModeAsync, None, None, CurrentTime);
    
        XSelectInput(display, root, ButtonPressMask) ;
        while(1){
        XNextEvent(display,&event);
        switch(event.type){
        case ButtonPress:
            switch(event.xbutton.button){
            case Button1:
            x=event.xbutton.x;
            y=event.xbutton.y;
            button=Button1;
            break;
    
            case Button3:
            x=event.xbutton.x;
            y=event.xbutton.y;
            button=Button3;
            break;
            default:
            break;
    
            }
            break;
        default:
            break;
        }
        if(x>=0 && y>=0)break;
        }
        if(button==Button1)printf("leftclick at %d %d \n",x,y);
        else printf("rightclick at %d %d \n",x,y);
        XCloseDisplay(display);
        return 0;
    }
    

提交回复
热议问题