Simulate a key held in Java

I am looking to simulate the action of holding a keyboard key for a short period of time in Java. I would expect the following code to hold the A key for 5 seconds, but it only presses it once (it produces a single "a" when testing in Notepad). Any idea if I need to use something else, or if I just use the awt.Robot class here incorrectly?

Robot robot = null; robot = new Robot(); robot.keyPress(KeyEvent.VK_A); Thread.sleep(5000); robot.keyRelease(KeyEvent.VK_A); 
+3
source share
3 answers

Thread.sleep () stops the current thread (the thread that holds the key) from executing.

If you want it to hold the key for a given period of time, perhaps you should run it in a parallel thread.

Here is a suggestion that will circumvent the Thread.sleep () problem (uses the command template so that you can create other commands and change them as you see fit):

 public class Main { public static void main(String[] args) throws InterruptedException { final RobotCommand pressAKeyCommand = new PressAKeyCommand(); Thread t = new Thread(new Runnable() { public void run() { pressAKeyCommand.execute(); } }); t.start(); Thread.sleep(5000); pressAKeyCommand.stop(); } } class PressAKeyCommand implements RobotCommand { private volatile boolean isContinue = true; public void execute() { try { Robot robot = new Robot(); while (isContinue) { robot.keyPress(KeyEvent.VK_A); } robot.keyRelease(KeyEvent.VK_A); } catch (AWTException ex) { // Do something with Exception } } public void stop() { isContinue = false; } } interface RobotCommand { void execute(); void stop(); } 
+4
source

Just keep clicking?

 import java.awt.Robot; import java.awt.event.KeyEvent; public class PressAndHold { public static void main( String [] args ) throws Exception { Robot robot = new Robot(); for( int i = 0 ; i < 10; i++ ) { robot.keyPress( KeyEvent.VK_A ); } } } 

I think the answer provided by Edward will do !!

+1
source

There is no keyDown event in java.lang.Robot. I tried this on my computer (testing on a console under Linux, not using notepad), and it worked, producing a line. Perhaps this is just a problem with NotePad?

0
source

Source: https://habr.com/ru/post/1403387/


All Articles