问题
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