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)
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:On a UK keyboard (which I’m using), the
"character is shifted2, which is why I’m usingKeyEvent.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 useVK_QUOTEinstead ofVK_2.I also found that releasing the
VK_SHIFTkeypress was necessary to avoid all sorts of weirdness with Windows thinking the Shift key was still held down.