javasendkeysawtrobot

Robot's keyPress() doesn't work as should


I need help with Robot class in Java. I have the following code:

public static void main(String[] args) throws AWTException {
    Robot r = new Robot();
    r.delay(3000);
    r.keyPress(KeyEvent.VK_7);
    r.delay(5000);
    r.keyRelease(KeyEvent.VK_7);
}

From what I understand, this code has to press "7" and release it after 5 seconds. But it presses "7" and then releases it immediately. So, Robot class doesn't press and release after a while, but it fires the key once instead.

How do I make my Java application to hold a key for few seconds, then release?


Solution

  • So, after researching this topic closely, I have concluded that java.awt.Robot class just doesn't have the functionality to "hold" down the key.

    The answer to a similar question (Simulate a key held down in Java), which recommended me to create a loop of constantly repeating keyPress events, didn't satisfy me, since I needed a real key-hold simulation.

    I also tried using this library with no success:

    Thread.sleep(3000);
    Keyboard.sendKeyDown(KeyEvent.VK_7);
    Thread.sleep(5000);
    Keyboard.sendKeyUp(KeyEvent.VK_7);
    

    Finally, I solved my issue via winKeyboard. But here's an important note:

    I was developing a bot for a game, and was not trying to hold a key inside any text editor and see how it's continually filling the line with characters. If you'll try to test holding button within a text editor, it won't work, because text editors repeated key presses are working differently from normal keyboard events listeners in games. But it's a different topic.

    Solution:

    Keyboard keyboard = new Keyboard();
    
    Thread.sleep(3000);
    keyboard.winKeyPress(ScanCode.DIK_7);
    Thread.sleep(5000);
    keyboard.winKeyRelease(ScanCode.DIK_7);
    

    Another thing to note is that sometimes, to make the bot work in games, you need to run your application as administrator, otherwise it might not work.