How to simulate a real mouse click using java?

前端 未结 6 1640
清酒与你
清酒与你 2020-11-27 14:44

I\'m attempting to perform a mouse click in Java, to click something in an external program. To do this, I\'m using java.awt.robot, and the following code:

6条回答
  •  鱼传尺愫
    2020-11-27 15:33

    it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.

    jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
    import java.awt.event.*;
    import java.awt.Robot;
    public class test {
     public static void main(String args[]) {
      Robot bot = null;
      try {
       bot = new Robot();
      } catch (Exception failed) {
       System.err.println("Failed instantiating Robot: " + failed);
      }
      int mask = InputEvent.BUTTON1_DOWN_MASK;
      bot.mouseMove(100, 100);
      bot.mousePress(mask);
      bot.mouseRelease(mask);
     }
    }
    

    I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.

    otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).

    [added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?

提交回复
热议问题