Linux, how to capture screen, and simulate mouse movements

前端 未结 4 929
春和景丽
春和景丽 2020-12-13 07:41

I need to capture screen (as print screen) in the way so I can access pixel color data, to do some image recognition, after that I will need to generate mouse events on the

4条回答
  •  时光取名叫无心
    2020-12-13 08:04

    //sg
    
    //Solution using Xlib for those who use Linux
    #include 
    #include
    #include
    #include 
    #include 
    
    #include 
    
    #include 
    #include 
    
    void mouseClick(int button)
    {
        Display *display = XOpenDisplay(NULL);
    
        XEvent event;
    
        if(display == NULL)
        {
            fprintf(stderr, "Cannot initialize the display\n");
            exit(EXIT_FAILURE);
        }
    
        memset(&event, 0x00, sizeof(event));
    
        event.type = ButtonPress;
        event.xbutton.button = button;
        event.xbutton.same_screen = True;
    
        XQueryPointer(display, RootWindow(display, DefaultScreen(display)), &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
    
        event.xbutton.subwindow = event.xbutton.window;
    
        while(event.xbutton.subwindow)
        {
            event.xbutton.window = event.xbutton.subwindow;
    
            XQueryPointer(display, event.xbutton.window, &event.xbutton.root, &event.xbutton.subwindow, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
        }
    
        if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Error\n");
    
        XFlush(display);
    
        usleep(100000);
    
        event.type = ButtonRelease;
        event.xbutton.state = 0x100;
    
        if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Error\n");
    
        XFlush(display);
    
        XCloseDisplay(display);
    }
    int main(int argc,char * argv[]) {
    
        int x , y;
        x=atoi(argv[1]);
        y=atoi(argv[2]);
        Display *display = XOpenDisplay(0);
    
        Window root = DefaultRootWindow(display);
        XWarpPointer(display, None, root, 0, 0, 0, 0, x, y);
        mouseClick(Button1);
        XFlush(display);
        XCloseDisplay(display);
        return 0;
    }
    

    Build it and then to simulate a click at x ,y do:

    $ ./a.out x y
    

    i.e.

    $ g++ -lX11 sgmousesim2.cpp

    $ ./a.out 123 13

    Just in case you are still interested.

提交回复
热议问题