(OSX)我试图粘贴字符串“Hello World!”从我的剪贴板到单独的应用程序。 String被复制到我的剪贴板,我可以手动粘贴它,但机器人只键入“v”而不是同时按下VK_META + VK_V键。
public static void sendString() throws Exception {
Thread.sleep(3000);
String text = "Hello World!";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
} catch(java.awt.AWTException awte) {
System.out.println("AWTException");
}
}
答案 0 :(得分:0)
要确保命令的顺序,请在它们之间添加延迟:
try{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.delay(500); // 200~500
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
} catch(java.awt.AWTException awte) {
System.out.println("AWTException");
}