java中的机器人(自动按键)

时间:2016-06-11 17:24:10

标签: java awtrobot

所以我想创建一个简单的java程序,按下键后按键,然后输入。和重复这个永恒3秒我的代码如下:`

public static void main(String[] args) {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_T);
                robot.keyRelease(KeyEvent.VK_T);
                robot.keyPress(KeyEvent.VK_KP_UP);
                robot.keyRelease(KeyEvent.VK_KP_UP);
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }, 3, 3, TimeUnit.SECONDS);
}

` 它按T,但在那之后我得到一个例外...

java.lang.IllegalArgumentException: Invalid key code
    at sun.awt.windows.WRobotPeer.keyPress(Native Method)
    at java.awt.Robot.keyPress(Unknown Source)
    at Main$1.run(Main.java:21)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

` 请帮我解决一下。

1 个答案:

答案 0 :(得分:0)

看起来Java 不支持Windows上的键盘绑定。 Bug Report

我在Windows上尝试过但没有成功。唯一的方法是使用VK_UP代替VK_KP_UP。如果您不需要指定键盘,则可以使用:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_T);
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);