keyboard - Issue with java.awt.Robot KeyEvent for Special Characters (e.g., : and ) - Stack Overflow
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:
- Verified the KeyEvent.VK_* constants for : and /.
- Used Shift combinations for : and other special characters.
- Confirmed the keyboard layout is correct.
- Tried alternative approaches like hardcoding the keycodes.
Questions:
- Why is the java.awt.Robot throwing an Invalid key code exception for these characters?
- Is there a more robust way to handle typing special characters with Robot across different keyboard layouts?
- 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:
- Verified the KeyEvent.VK_* constants for : and /.
- Used Shift combinations for : and other special characters.
- Confirmed the keyboard layout is correct.
- Tried alternative approaches like hardcoding the keycodes.
Questions:
- Why is the java.awt.Robot throwing an Invalid key code exception for these characters?
- Is there a more robust way to handle typing special characters with Robot across different keyboard layouts?
- 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 |2 Answers
Reset to default 0Yes 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 );
- Win11革命性新变化来了!31年的NTFS被取代:ReFS将成默认文件系统
- 谷歌继续封死华为后路,Mate 30无法安装谷歌服务
- 台北电脑展10大杀手级电脑硬件
- 软件定义网络:正在进行的网络变革
- flutter - Alert + Data FCM message does not always trigger FirebaseMessaging.onMessage on iOS - Stack Overflow
- node.js - nodejspostgres connect issue - Stack Overflow
- php - Laravel RouteServiceProvider missing in appProviders directory - Stack Overflow
- c - Dereferencing a valid pointer results in an error - Stack Overflow
- Windows Powershell: check if a symlink is "broken" - Stack Overflow
- android - How to setImageCaptureResolutionSelector() in CameraController? - Stack Overflow
- c++ - Microbenchmark - backward iteration results in fewer cache misses - Stack Overflow
- reflection - java.lang.reflect.field.set(obj,value) fails for applicationscoped - Stack Overflow
- javascript - filter out object in array if object key value is null - Stack Overflow
- assembly - Why could not I apply call gate successfully? - Stack Overflow
- php - Laravel Defer on API requests - Stack Overflow
- reactjs - How to keep the modal open after navigating and returning from a certain screen in react native? - Stack Overflow
- window - Strawberry Perl doesn't include Win32::shortcut? - Stack Overflow
KeyEvent.getExtendedKeyCodeForChar(c)
returns513
(VK_COLON) for the colon (which is the correct "event" code). This means with your logic it would invokerobot.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 whygetExtendedKeyCodeForChar
did not return VK_UNDEFINED. – Computable Commented yesterday