Search code examples
javajunit4awtrobot

Why is `robot.keyRelease(KeyEvent.VK_CONTROL)` necessary?


When using Robot class, what is the meaning of:

robot.keyRelease(KeyEvent.VK_CONTROL);

Shouldn't the code below be sufficient to send the event?

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);

Solution

  • keyPress will send an event that a key has been pressed down. keyRelease will send the event that the key has been released. If you want to simulate typing, you might want to do something like:

    public class SuperRobot extends Robot {
        public void typeKey(int keyCode) {
            keyPress(keyCode);
            delay(20);
            keyRelease(keyCode);
        }
    }
    
    public static void main(String[] args) {
        try {
            SuperRobot r = new SuperRobot();
            // Now, let's press Ctrl+A
            r.keyPress(KeyEvent.VK_CONTROL);
            r.typeKey(KeyEvent.VK_A);
            r.keyRelease(KeyEvent.VK_CONTROL);
        } catch (Exception ex) { // Either AWTException or SecurityException
            System.out.println("Oh no!");
        }
    }
    

    Note that to type something with a mask, like Ctrl+A, we first press down Ctrl, then simulate pressing and releasing A, then release Ctrl. As a general rule, the robot should more-or-less exactly simulate what you as a user would do.