问题
I'm trying to use Robot in order to switch apps, and then enter some text. To do this (on my mac), I'm pressing Meta, Tab, and then releasing Tab, Meta in this order:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_META);
This works, but only occasionally (about every 5 or six presses). I've tried calling Thread.wait() inbetween press and release, but this has no effect. Neither does trying to mask Tab with META_DOWN_MASK. I also tried using the JavaFX Robot (com.sun.glass.ui.Robot), but the JavaFX version doesn't work at all.
回答1:
Ah.. Seems that I need to specify a delay between the events. Updated:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.delay(300);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_META);
来源:https://stackoverflow.com/questions/48553913/switching-apps-on-mac-with-awt-robot-only-sometimes-works