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

1

2

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)
Mele answered 12/8, 2012 at 14:40 Comment(2)
Works for me on Ubuntu 12.04 x64. However, it only prints a single quote instead of a double.Milburn
possible duplicate of Why are some KeyEvent keycodes throwing "IllegalArgumentException: Invalid key code"?Aeropause
A
6

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.

Aeropause answered 12/8, 2012 at 15:13 Comment(2)
Aha, that's also why it was only putting a single quote on my machine. You should always remember to release a key after pressing it with a Robot, if you don't (at least on my machine) it'll continue to send that key event, resulting in hundreds of quotes appearing.Milburn
Is there any non-layout-dependent way? (Without using clipboard)Greet

© 2022 - 2024 — McMap. All rights reserved.