Reputation: 493
My current project involves automation using Java's Robot class, to simulate key presses.
My problem is that certain keycodes are invalid to pass to the Robot's keypress(int keycode)
method.
After reading the solution to this question: Why are some KeyEvent keycodes throwing IllegalArgumentException: Invalid key ocode, I started modifying my code, changing certain symbols like £ (VK_DOLLAR)
to VK_SHIFT + VK_3
, & (VK_AMPERSAND)
to VK_SHIT + VK_7
, etc ...
My question, however is how to determine what key gives what symbol when combined with shift, since different keyboards (and often times different keyboard configurations from the OS) change these.
A typical example is the @ (at symbol) and " (double quote)
. VK_SHIFT + VK_2
may be the at symbol on some systems while maybe a double quote on others.
Is there anyway in Java to check, prior to invoking the Robot keypress, on which key a symbol relies ?
Thanks in advance.
Upvotes: 1
Views: 2287
Reputation: 371
I already went through IllegalArgumentException when using robots. It's because of your keyboard layout. My solution was to use Alt codes:
public static void alt(int event1, int event2, int event3, int event4) throws Exception {
Robot bot = new Robot();
bot.delay(50); //Optional
bot.keyPress(KeyEvent.VK_ALT);
bot.keyPress(event1);
bot.keyRelease(event1);
bot.keyPress(event2);
bot.keyRelease(event2);
bot.keyPress(event3);
bot.keyRelease(event3);
bot.keyPress(event4);
bot.keyRelease(event4);
bot.keyRelease(KeyEvent.VK_ALT);
}
It makes easy to send Alt codes.
For example, if you want an ampersand just use alt(KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD3, KeyEvent.VK_NUMPAD8);
You just got to make sure Num Lock is on.
A useful site to get the alt codes you'll need is http://www.alt-codes.net/
Upvotes: 1