Using JNA or JNI to simulate keys held in Windows

I want to simulate a keystroke in Java. Others tried to use Robot. This allows only atomic keystrokes, where I want to simulate key holding (for a second, say) and release. Therefore, I need to use JNA or JNI.

I researched JNative, but it looks like it is consuming key events at the OS level, rather than generating them at the OS level. How can I generate such events from Java?

thanks

+4
source share
2 answers

From JavaDoc:

void java.awt.Robot.keyPress(int keycode) Presses a given key. The key should be released using the keyRelease method. 

EDIT: adding sample:

  Robot robot = new Robot(); System.out.println("You have 2 seconds to jump to the target window..."); Thread.sleep(2000); robot.keyPress( KeyEvent.VK_A); robot.keyRelease( KeyEvent.VK_A); robot.keyPress( KeyEvent.VK_SHIFT); robot.keyPress( KeyEvent.VK_A); robot.keyRelease( KeyEvent.VK_SHIFT); robot.keyRelease( KeyEvent.VK_A); Thread.sleep(2000); 

Exit to the target window:

  aA 

(I know that this is not what you want, but I added it as a reference for future readers, so they don’t think there is an error in JavaDoc or Robot)

+2
source

In fact, using Robot, you can hold down the key for the second.

 Robot r = ... r.keyPress(KeyEvent.VK_A); Thread.sleep(1000); r.keyRelease(KeyEvent.VK_A); 
+2
source

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


All Articles