简体   繁体   English

什么时候java.awt.Robot无法点击?

[英]When will the java.awt.Robot fail to click?

I use java.awt.Robot to perform some mouse behaviors on my PC. 我使用java.awt.Robot在PC上执行一些鼠标行为。 The code is simple like below: 代码很简单,如下所示:

import java.awt.Robot;
import java.awt.event.InputEvent;

public class RobotProxy {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        RobotProxy robotProxy = new RobotProxy();
        try {
            robotProxy.foo();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Exception there...");
        }
    }

    public void foo() throws Exception{
        Thread.sleep(3000);
        Robot robot = new Robot();
        robot.mouseMove(501, 296);

        leftClick(robot);

        robot.mouseMove(505, 296);

        leftClick(robot);

        robot.mouseMove(509, 296);

        leftClick(robot);
    }

    public void leftClick(Robot robot) throws Exception{
        Thread.sleep(1000);

        System.out.println("before Click...");

        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);

        System.out.println("after Click...");
    }

}

You can find that I use the combination of java.awt.Robot.mousePress(InputEvent.Button1_MASK) and java.awt.Robot.mouseRelease(InputEvent.Button1_MASK) to perform the mouse left click behavior. 您可以发现我结合使用java.awt.Robot.mousePress(InputEvent.Button1_MASK)java.awt.Robot.mouseRelease(InputEvent.Button1_MASK)来执行鼠标左键单击行为。

It works fine at most time but fails sometimes. 它在大多数时间都能正常工作,但有时会失败。 For example, the left click behavior for a kind of software's check box will fail. 例如,一种软件复选框的左击行为将失败。 I can make sure I send the click command to java.awt.Robot but just nothing happens. 我可以确保将click命令发送到java.awt.Robot,但是什么也没有发生。 What's more incredible is that java.awt.Robot.mouseMove(int x, int y) still works in that situation. 更令人难以置信的是,在这种情况下java.awt.Robot.mouseMove(int x,int y)仍然有效。

PC's OS is Windows8.1 PC的操作系统是Windows8.1

The software is not market available and it's just a Windows native app written by cpp. 该软件没有市场可用,它只是cpp编写的Windows本机应用程序。 The button on the software can be clicked but not for check box. 可以单击软件上的按钮,但不能单击复选框。

If the situation makes you confused, pls just tell me when will the java.awt.Robot fail to click. 如果情况使您感到困惑,请告诉我java.awt.Robot何时无法点击。 Thanks for your help in advance. 感谢您的帮助。

The problem is there is no delay between the robot.mousePress and robot.mouseRelease commands. 问题是robot.mousePressrobot.mouseRelease命令之间没有延迟。

Here is an example of what you could add in between the two to fix the issue Thread.sleep(100); 这是您可以在两者之间添加解决问题的示例Thread.sleep(100); a delay for 100ms. 延迟100毫秒。 about as fast as you can hear, click click 大约听到的最快速度, 请单击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM