views:

734

answers:

5

Hi, is there any free and open source java library for capturing active window screenshot?

I want to use it to capture any active window, not only SWING windows.

Thanks.

A: 

Why not use the Robot class?

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;


public class ActiveWindowScreenShot
{
 /**
  * Main method
  * 
  * @param args (not used)
  */
 public static void main(String[] args)
 {
  Robot robot;

  try {
   robot = new Robot();
  } catch (AWTException e) {
   throw new IllegalArgumentException("No robot");
  }

  // Press Alt + PrintScreen
  // (Windows shortcut to take a screen shot of the active window)
  robot.keyPress(KeyEvent.VK_ALT);
  robot.keyPress(KeyEvent.VK_PRINTSCREEN);
  robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
  robot.keyRelease(KeyEvent.VK_ALT);

  System.out.println("Image copied.");
 }
}
animeaime
+2  A: 

Okay, you need to get the handle to the window, see this post for code: http://stackoverflow.com/questions/386792/in-java-swing-how-do-you-get-a-win32-window-handle-hwnd-reference-to-a-window

After that, get the window size using the handle, and finally capture the image using the following code:

try {
    Robot robot = new Robot();
    Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage bufferedImage = robot.createScreenCapture(captureSize);
}
catch(AWTException e) {
    System.err.println("Someone call a doctor!");
}

It's complex, but there's no real Java API. Similar post that came to the same conclusion: http://www.daniweb.com/forums/thread101597.html#

Chris Dennett
A: 

Thanks Chris, excellent answer.

Additionally, to easily save that image to file, you can use the javax.imageio.ImageIO class. E.g.

ImageIO.write(bufferedImage, "png", new File("C:\\tmp\\out.png"));

Good thing that this is all in the standard JRE and is relatively simple to achieve. I can't believe there are capture libraries (e.g. JxCapture) - albieit with some additional capabilities - retailing for $375!

David Turner
A: 

how can i get this 'bufferedImage'?

John
A: 

Is there a way to get the handle of a window under Linux ?

The provided example was for Win32

Mike