How to get a screenshot of any Linux / Windows application running outside of the JVM

Is it possible to use Java to take a screenshot of an application external to Java, such as VLC / Windows Media Player, save it as an image object, and then display it in JLabel or something similar? Does anyone know if this is possible, and if anyone has a general idea on how to do this?

Note. I just need to figure out how to get a screenshot and save it as part of the shape of the Image object. After that, I can use, manipulate it, display it, etc.

+6
source share
2 answers

Here is the answer for Windows (not sure if alt + printScr works on linux: P)

I guess one way to achieve this

1. using the Robot class to run the alt + printScreen command (this captures the active window on the clipboard)

2. read the clipboard

Here are two pieces of code that do this. I actually did not try, but something that I put together.

Code to Fire Commands for the Active Clipboard Window

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

Code to read image on clipboard

 // If an image is on the system clipboard, this method returns it; // otherwise it returns null. public static 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; } 

You can control the control as you need! Let me know if this works for you. but it is definitely on my todo to try it!

+3
source

You can get a screenshot of the entire screen using a class called Robot . Unfortunately, you cannot get the location and size of windows belonging to other applications using a pure Java solution. For this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.

+2
source

Source: https://habr.com/ru/post/904448/


All Articles