Why is `robot.keyRelease(KeyEvent.VK_CONTROL)` necessary?
Whe开发者_StackOverflow中文版n 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);
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.
robot.keyRelease(KeyEvent.VK_CONTROL);
For Releasing the press effect on the key, If you have pressed a key using robot.keyPress(KeyEvent.VK_CONTROL); Then you should Release it too, otherwise once your java application runs, your keyboard has will continue with virtually CTRL key pressed.
精彩评论