Simulate a print screen under Windows

I know that we can simulate a print screen with the following code:

robot.keyPress(KeyEvent.VK_PRINTSCREEN); 

.. but then how to return some BufferedImage ?

I found some method on Google called getClipboard() , but Netbeans returned me some error on this (I cannot find the character).

I'm sorry to ask this, but can someone show me a working code on how returning from this key presses BufferedImage , which I could save?

+4
source share
1 answer

This will not necessarily give you a BufferedImage , but it will be Image . This uses Toolkit.getSystemClipboard .

 final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) { final Image screenshot = (Image) clipboard.getData(DataFlavor.imageFlavor); ... } 

If you really need a BufferedImage , try the following ...

 final GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); final BufferedImage copy = config.createCompatibleImage( screenshot.getWidth(null), screenshot.getHeight(null)); final Object monitor = new Object(); final ImageObserver observer = new ImageObserver() { public void imageUpdate(final Image img, final int flags, final int x, final int y, final int width, final int height) { if ((flags & ALLBITS) == ALLBITS) { synchronized (monitor) { monitor.notifyAll(); } } } }; if (!copy.getGraphics().drawImage(screenshot, 0, 0, observer)) { synchronized (monitor) { try { monitor.wait(); } catch (final InterruptedException ex) { } } } 

Although, I really need to ask why you are not just using Robot.createScreenCapture .

 final Robot robot = new Robot(); final GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); final BufferedImage screenshot = robot.createScreenCapture(config.getBounds()); 
+8
source

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


All Articles