Hi,
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:
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
saveToImage((RenderedImage)getClipboard(),targetLocation);
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.
Thanks,
Anuj Sharma