4

I am trying to move the cursor around a computer with multiple monitors. However, when I use just the mouseMove function from robot it won't function properly. After some research I found this stackoverflow post and it almost works. But now it seems like the GraphicsConfiguration and Robot both see a different main monitor. This means that 0,0 is 1920,0 for the other. So my mouse always transfers to the other screen when I try to use it. Is there any universal way of fixing this issue and thus moving the cursor relative to it's current position?

I hope someone can help me.

My code:

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) { }
}
Community
  • 1
  • 1
Aronnn
  • 63
  • 1
  • 6

1 Answers1

1

Try

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

According to the documentation, it should make the robot use the same GraphicsDevice as MouseInfo.getPointerInfo() is using.

Erhannis
  • 4,256
  • 4
  • 34
  • 48