java stimulate a keyboard key press (long press specifically) currently using java.awt.Robot

Viewed 31

Currently I am using java.awt.Robot to perform key presses. The application I am developing requires long presses. I can't just use a loop and perform repeated presses. Every question posted on this website provides one of the three solutions -

make the thread go to sleep -

public static void main(String[] args) {
    try {
        Robot robot = new Robot();
        Thread.sleep(5000);
        int key = KeyEvent.VK_W;
        robot.keyPress(key);
        Thread.sleep(5000);
        robot.keyRelease(key);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

try using the robot's delay function -

public static void main(String[] args) {
    try {
        Robot robot = new Robot();
        Thread.sleep(5000);
        int key = KeyEvent.VK_W;
        robot.keyPress(key);
        robot.delay(5000);
        robot.keyRelease(key);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

the third one is the repeated pressing which isn't something I can implement into my project.

1st and 2nd don't work and third is unusable for my project.

I am using a windows 11 machine with 22H2 update (i.e. latest version)

2 Answers

I did some research, and apparently it is not possible. I tried too with SendInput() function using Windows API with C++, and the result is the same : the key is pressed, but does not repeat.

The problem might be that our keyPress event sent to the OS is missing informations (a repeat flag?), and those APIs will not let us change it.

Weirdly enough, the code I posted in the question actually works. Kinda. Here's what I found out -

  • I tested out these functions in multiple text editors but, they never worked.
  • For the above code, the output I received was always a single character w instead of something like wwwwwwwwwwwwwwwwwwwwwwwwwwww which I expected.
  • But somehow, when I tried this code while being inside a game (shadow of tomb raider), surprisingly it worked. My character was running for the specified interval.

I don't know what the issue is. My goal was to get it to work inside games. So, I guess it works already?

Related