java.awt.Robot.keyPress throws IllegalArgumentException when when pressing quotation mark key

痞子三分冷 提交于 2019-12-02 05:47:01

问题


When you try to use Robot.keyPress to type a " (double quotation mark) it throws a java.lang.IllegalArgumentException: Invalid key code.

How can I fix or get around this?

If it helps, I am currently on Windows.

Test code:

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Test {
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        try {
            robot.keyPress(KeyEvent.VK_QUOTEDBL);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Exception:

java.lang.IllegalArgumentException: Invalid key code
    at sun.awt.windows.WRobotPeer.keyPress(Native Method)
    at java.awt.Robot.keyPress(Robot.java:358)

回答1:


I think you're getting an error because there isn't a " key on your keyboard. " will almost certainly be on one of the keys of your keyboard but it will quite probably be shifted. Instead of trying to 'press' ", you should be 'pressing' Shift and the 'base' character for that key, i.e. the one you get if you type that key on its own.

I found that running the following class in a command-prompt left me with a " character:

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Test {
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        try {
            robot.keyPress(KeyEvent.VK_SHIFT);
            robot.keyPress(KeyEvent.VK_2);
            robot.keyRelease(KeyEvent.VK_SHIFT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

On a UK keyboard (which I'm using), the " character is shifted 2, which is why I'm using KeyEvent.VK_2. It may be in other places on other keyboards - if I remember correctly, it's shifted single-quote on a US keyboard. In that case, you would use VK_QUOTE instead of VK_2.

I also found that releasing the VK_SHIFT keypress was necessary to avoid all sorts of weirdness with Windows thinking the Shift key was still held down.



来源:https://stackoverflow.com/questions/11923033/java-awt-robot-keypress-throws-illegalargumentexception-when-when-pressing-quota

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!