Switching Apps on Mac with AWT Robot only sometimes works

匆匆过客 提交于 2019-12-31 04:22:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!