I am writing a program to capture a screenshot of the screen when I press a particular button on my keyboard. The problem that I have is that the program won't take my screenshot if its in the background. The screenshot will only capture if my program is in the foreground.
I'm using the robot class to capture and save the screenshot. I have my program below...
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.KeyEventDispatcher;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
public class FullScreenCaptureExample{
private static int num = 1;
public static void main(String[] args) throws AWTException{
final File file = new File("C:\\screenshots");
final Robot rbt = new Robot();
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setBounds(100, 100, 190, 73);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
if(!file.exists()){
file.mkdir();
}
KeyEventDispatcher dispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_5){
try {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenshot = rbt.createScreenCapture(screenRect);
ImageIO.write(screenshot, "jpg", new File(file + "/" + num + ".jpg"));
num++;
System.out.println("screenshot taken");
} catch (Exception e1) {
e1.printStackTrace();
}
}
return false;
}
};
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
}
I'm wondering if there is a java class or some other way to get user input without having the program run in the foreground.
Thank you