Using Java Robot class for simulating alt+right arrow, draws signs instead of going to next page

StackOverflow https://stackoverflow.com/questions/23526799

  •  17-07-2023
  •  | 
  •  

Question

I'm building a small Java application that has two buttons.
One of the buttons should change the chrome's page to the previous one,
and the second should change to the next page.
I'm using Java Robot class in order to stimulate the shortcuts that perform this action.

// next page (alt + right arrow)
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_RIGHT);
robot.keyRelease(KeyEvent.VK_RIGHT); 
robot.keyRelease(KeyEvent.VK_ALT);

The code works, but when the address bar in chrome is clicked,
and then one of the buttons is triggered, then instead of jumping to the next\previous page, strange signs are written to the address bar. The signs are ♠ ♦.

I tried also to change the order between the commands, it didn't helped.

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_RIGHT);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_RIGHT); 
Was it helpful?

Solution

It seems there is a bug with java.util.Robot always using numpad [arrow] keys, just try alt+numpad4 or numpad6 manually. I couldn't find the original bug, here are some links:

As a work-around, you'd try to remove focus from the address bar, the following worked for me:

robot.keyPress(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_ALT);
robot.delay(1); // seems to be required for the event to be registered
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_LEFT);
robot.keyRelease(KeyEvent.VK_ALT);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top