Java uses mouseMove with multiple monitors

I am trying to move the cursor around a computer with multiple monitors. However, when I use only the mouseMove function from the robot, it will not function properly. After doing some research, I found https://stackoverflow.com/a/3188671/ and it almost works. But now it looks like GraphicsConfiguration and Robot are seeing a different main monitor. This means that 0.0 is 1920.0 for another. Therefore, my mouse always switches to another screen when I try to use it. Is there a universal way to solve this problem and thus move the cursor relative to the current position?

Hope someone can help me.

My code is:

public static void moveCursor(int dx, int dy) {
    try {
        PointerInfo pi = MouseInfo.getPointerInfo();
        Point mp = pi.getLocation();
        GraphicsConfiguration gc = pi.getDevice().getDefaultConfiguration();
        Rectangle bounds = gc.getBounds();
        Point virtualPoint = new Point(mp);
        virtualPoint.x -= bounds.x;
        virtualPoint.y -= bounds.y;
        Robot r = new Robot();
        r.mouseMove(virtualPoint.x + dx, virtualPoint.y + dy);
    } catch (AWTException ex) { }
}
+4
1

Try

Robot r = new Robot(MouseInfo.getPointerInfo().getDevice());

, GraphicsDevice, MouseInfo.getPointerInfo().

+1

Source: https://habr.com/ru/post/1529864/


All Articles