I want to run a java program and have it simulate keyboard presses. So it could for example, type some text on a focused input box. Is this possible?
-
3The Robot class can do this for you, but if you want to do other more fancy interactions with an outside process, you may wish to use a different language as Java does not get very close to the OS by design.– Hovercraft Full Of EelsOct 12, 2011 at 20:14
-
You mean simulate keyboard presses on an input box of your own program, or from an other application ?– Pierre SevrainOct 12, 2011 at 20:25
Add a comment
|
1 Answer
java.awt.Robot might help.
Here's a simple sample code snippet from Java Tips:
try {
Robot robot = new Robot();
// Simulate a mouse click
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
// Simulate a key press
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
} catch (AWTException e) {
e.printStackTrace();
}
-
5If you need to achieve this while using JavaFX use FXRobot. The API is quite similar. Jan 27, 2014 at 6:40
-
1can we write on to another application using robot class? like a text box in another application that is running along with this. May 22, 2015 at 7:34
-
-
6@partho
robot.keyPress(KeyEvent.VK_A);robot.keyPress(KeyEvent.VK_B);robot.keyRelease(KeyEvent.VK_A);robot.keyRelease(KeyEvent.VK_B);
Aug 24, 2016 at 12:36 -
From Robot class javadoc "Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. For example, X-Window systems will throw the exception if the XTEST 2.2 standard extension is not supported (or not enabled) by the X server."– nyholkuAug 24, 2021 at 5:10