I am trying to get a screenshot of the active window on the screen, for which unfortunately Java does not have an API. It allows me to capture the screenshot of the whole screen but not of the active window.

Now, I did a bit of workaround but it is not working as expected. What I did was first press the Alt+PrntScrn keys using the robot class object. Then I get the contents from the clipboard and save the image to a file.

The code is working fine, however it is not getting me the latest image. It gets the last screenshot taken. So the first time the code is run, the image file size is 0kb, next time the code runs it gets the image that was previously taken.
Here is the code:


public Image getClipboard() 
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
        try {
            if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) 
                Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
                return text;
        catch (UnsupportedFlavorException e) 
        catch (IOException e) 
        return null;

I am not sure what is happening, please advice.

Anuj Sharma

Perhaps it's a task switch thing? You could try a sleep(1000) after taking the screenshot but before accessing the clipboard?

Thanks James. You were right, it is a task switch thing. As you suggested, i put a sleep in between the screenshot and clipboard access and it worked. Now it is getting the right image.

This question has already been answered. Start a new discussion instead.