简体   繁体   中英

Robot in java (auto key press)

So I would like to make a simple java program that presses key T after that presses key up and after that enter. ANd repet this everz 3 secounds My code is the following: `

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);
}

` It presses T but after that I get an exception...

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)

` Please help me how to fix it.

It looks like that Java does not support keypad bindings on Windows. Bug Report

I tried it on Windows without success. The only way to do it is to use VK_UP instead of VK_KP_UP . If you do not need to specify the keypad up, this will work:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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