0
我試圖以編程方式將一些文本添加到系統剪貼板,將其粘貼到隨機應用程序並將剪貼板恢復到之前的狀態,但Java似乎有問題接着就,隨即。 在十次嘗試中,它絕不會超過八次粘貼文本,有時甚至會粘貼錯誤的文本(之前位於剪貼板中的文本)。以編程方式在Java中粘貼後恢復剪貼板
任何幫助將不勝感激!
public class ClipboardTestClass {
static Robot robot;
public static void main(String[] args) {
try {
robot = new Robot();
} catch (AWTException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i = 0; i< 10; i++){
enterString("Hello\n");
}
}
public static void enterString(String myString){
System.out.println("Trying to paste string \"" + myString + "\"");
StringSelection stringSelection = new StringSelection(myString);
//save clipboard content
Transferable clipboardContent = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
//enter new clipboard content
Toolkit.getDefaultToolkit().getSystemClipboard().setContents((Transferable) stringSelection, null);
//paste clipboard content with Robot class
robot.keyPress(VK_CONTROL);
robot.keyPress(VK_V);
robot.keyRelease(VK_CONTROL);
robot.keyRelease(VK_V);
//restore clipboard content
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(clipboardContent, null);
}
}