keyboard - Issue with java.awt.Robot KeyEvent for Special Characters (e.g., : and ) - Stack Overflow

时间: 2025-01-06 admin 业界

Description:

Hello everyone,

I'm working on a Java application where I use the java.awt.Robot class to simulate keyboard input. It works fine for most characters, but I'm encountering an issue when trying to type special characters such as : and /.

Here is the method I use to handle special characters:

private void digitarCaracterEspecial(Robot robot, char c) {
    try {
        switch (c) {
            case ':':
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.keyPress(KeyEvent.VK_SEMICOLON); // ':' = Shift + ';'
                robot.keyRelease(KeyEvent.VK_SEMICOLON);
                robot.keyRelease(KeyEvent.VK_SHIFT);
                break;
            case '/':
                robot.keyPress(KeyEvent.VK_SLASH); // Verifique o layout do teclado
                robot.keyRelease(KeyEvent.VK_SLASH);
                break;
            case '&':
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.keyPress(KeyEvent.VK_7); // '&' = Shift + '7' in US keyboard
                robot.keyRelease(KeyEvent.VK_7);
                robot.keyRelease(KeyEvent.VK_SHIFT);
                break;
            default:
                System.err.println("Unsupported special character: " + c);
        }
    } catch (Exception e) {
        System.err.println("Error while typing special character: " + c);
        e.printStackTrace();
    }
}

Problem:

When I attempt to type : or /, I encounter the following exception:

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

Here is a snippet of my test code:

Robot robot = new Robot();
String text = ":8080/";
for (char c : text.toCharArray()) {
    if (KeyEvent.getExtendedKeyCodeForChar(c) == KeyEvent.CHAR_UNDEFINED) {
        digitarCaracterEspecial(robot, c);
    } else {
        robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(c));
        robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(c));
    }
}

Environment:

  • OS: Windows 10
  • JDK Version: OpenJDK 21
  • Keyboard Layout: Brazilian ABNT2

What I’ve Tried:

  1. Verified the KeyEvent.VK_* constants for : and /.
  2. Used Shift combinations for : and other special characters.
  3. Confirmed the keyboard layout is correct.
  4. Tried alternative approaches like hardcoding the keycodes.

Questions:

  1. Why is the java.awt.Robot throwing an Invalid key code exception for these characters?
  2. Is there a more robust way to handle typing special characters with Robot across different keyboard layouts?
  3. Could this be a layout-specific issue (e.g., Brazilian ABNT2 vs. US keyboard)?

Any help or insights would be greatly appreciated. Thank you in advance!

Description:

Hello everyone,

I'm working on a Java application where I use the java.awt.Robot class to simulate keyboard input. It works fine for most characters, but I'm encountering an issue when trying to type special characters such as : and /.

Here is the method I use to handle special characters:

private void digitarCaracterEspecial(Robot robot, char c) {
    try {
        switch (c) {
            case ':':
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.keyPress(KeyEvent.VK_SEMICOLON); // ':' = Shift + ';'
                robot.keyRelease(KeyEvent.VK_SEMICOLON);
                robot.keyRelease(KeyEvent.VK_SHIFT);
                break;
            case '/':
                robot.keyPress(KeyEvent.VK_SLASH); // Verifique o layout do teclado
                robot.keyRelease(KeyEvent.VK_SLASH);
                break;
            case '&':
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.keyPress(KeyEvent.VK_7); // '&' = Shift + '7' in US keyboard
                robot.keyRelease(KeyEvent.VK_7);
                robot.keyRelease(KeyEvent.VK_SHIFT);
                break;
            default:
                System.err.println("Unsupported special character: " + c);
        }
    } catch (Exception e) {
        System.err.println("Error while typing special character: " + c);
        e.printStackTrace();
    }
}

Problem:

When I attempt to type : or /, I encounter the following exception:

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

Here is a snippet of my test code:

Robot robot = new Robot();
String text = "https://example.com:8080/";
for (char c : text.toCharArray()) {
    if (KeyEvent.getExtendedKeyCodeForChar(c) == KeyEvent.CHAR_UNDEFINED) {
        digitarCaracterEspecial(robot, c);
    } else {
        robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(c));
        robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(c));
    }
}

Environment:

  • OS: Windows 10
  • JDK Version: OpenJDK 21
  • Keyboard Layout: Brazilian ABNT2

What I’ve Tried:

  1. Verified the KeyEvent.VK_* constants for : and /.
  2. Used Shift combinations for : and other special characters.
  3. Confirmed the keyboard layout is correct.
  4. Tried alternative approaches like hardcoding the keycodes.

Questions:

  1. Why is the java.awt.Robot throwing an Invalid key code exception for these characters?
  2. Is there a more robust way to handle typing special characters with Robot across different keyboard layouts?
  3. Could this be a layout-specific issue (e.g., Brazilian ABNT2 vs. US keyboard)?

Any help or insights would be greatly appreciated. Thank you in advance!

Share Improve this question asked yesterday JamesBJamesB 5291 gold badge10 silver badges36 bronze badges 1
  • For me, on a US keyboard KeyEvent.getExtendedKeyCodeForChar(c) returns 513 (VK_COLON) for the colon (which is the correct "event" code). This means with your logic it would invoke robot.keyPress(513) which produces the noted exception. (The failure makes sense in that it is not a primary key (can't press ':') but what doesn't make sense is why getExtendedKeyCodeForChar did not return VK_UNDEFINED. – Computable Commented yesterday
Add a comment  | 

2 Answers 2

Reset to default 0

Yes the reason it is not working for you is most likely the keyboard layout being different. Since you are using Windows, you can use Alt codes with Numlock enabled since they are layout agnostic.

For example, the Alt code for backslash is ALT + 92. To type this using the Robot class, you would do something like :

Robot r = new Robot();
// start holding ALT
r.keyPress(KeyEvent.VK_ALT);
r.delay(50); // ms

// press 9
r.keyPress(KeyEvent.VK_NUMPAD9);
r.delay(50); // ms
r.keyRelease(KeyEvent.VK_NUMPAD9);
r.delay(50); // ms

// press 2
r.keyPress(KeyEvent.VK_NUMPAD2);
r.delay(50); // ms
r.keyRelease(KeyEvent.VK_NUMPAD2);
r.delay(50); // ms

// release ALT
r.keyRelease(KeyEvent.VK_ALT);

We use the following code to find out the numerical code that corresponds to each key, on my machine, "shift" corresponds to "16" and "/" to "55".

  addKeyListener( new KeyListener() {
     public void keyTyped( KeyEvent e ) { }

     public void keyReleased( KeyEvent e ) { }

     public void keyPressed( KeyEvent evt ) {
        String evento = evt.toString();    // event details 
        int keyCode = evt.getKeyCode();    // key number
        String keyText = evt.getKeyText( keyCode );   // key letter 
        System.out.println( "text = " + keyText + " code = " + keyCode );
     }
  } );

then we use the robot:

robot.keyPress( shiftValue );
robot.keyPress( keyValue );
robot.keyRelease( keyValue );
robot.keyRelease( shiftValue );