Raspel
Raspel

Reputation: 383

Restoring Clipboard after pasting programmatically in Java

I'm trying to programmatically add some text to the system clipboard, paste it to a random application from there and restore the clipboard to the state it was before, but Java seems to have a problem with that. Out of ten tries it never pastes the text more than eight times and sometimes even the wrong text (the text that was in the clipboard before) is pasted.

Any help would be greatly appreciated!

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);
    }
}

Upvotes: 0

Views: 469

Answers (2)

Dilip Muthukurussimana
Dilip Muthukurussimana

Reputation: 709

For String type content (ONLY!!!), I came up with this snippet:

import static java.awt.Toolkit.getDefaultToolkit;

public class Main {
    public static void main(String[] args) throws IOException, UnsupportedFlavorException {
        Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        // Save the old data
        String oldData = (String) systemClipboard.getContents(null).getTransferData(DataFlavor.stringFlavor);

        // Now lets put some new data to clipboard!
        StringSelection stringSelection = new StringSelection("Jai Hind!! Vandee Maatharam!!!!");
        systemClipboard.setContents(stringSelection, null);

        // Lets print the clipboard content
        String newData = (String) 
        systemClipboard.getContents(null).getTransferData(DataFlavor.stringFlavor);
        System.out.println("Here is the new data: [" + newData + "]");

        // Now setting back the old clipboard content
        StringSelection oldDataSelection = new StringSelection(oldData);
        systemClipboard.setContents(oldDataSelection, null);

        //Now hit CTRL+V in an editor and you should get back the old clipboard content (NOTE: Only String Contents!!!)
}

Upvotes: 0

Chris Thornton
Chris Thornton

Reputation: 15817

This will never work reliably. You would have to handle all formats, no matter what the size. Read up on Delayed Rendering (where the data doesn't actually exist on the clipboard at all until a request is made to paste it), and you will start to understand the problem. Some apps, like Excel, can provide the data in 25+ formats, some of them very large and complex. There isn't time or RAM to render them all. So you can't restore the clipboard the way it was. And you can't update the clipboard at all, without triggering other clipboard-aware apps from doing "their thing".
And lastly, you should not be using the clipboard this way. The clipboard is a shared resource, provided for the convenience of the USER, not the programmer.
Find another way.

Upvotes: 2

Related Questions