簡體   English   中英

如何截取任何 java 本機應用程序而不將其帶到 Java 中的前台?

[英]How to take screenshot of any java native application without bringing it to foreground in Java?

我想截取 java 本機應用程序(任何框架 AWT、Swing、JavaFx)的屏幕截圖,而不將其帶到前台 是否有任何特定於框架的方法可用於此?

我試過使用 Robot class 來獲取屏幕截圖

private static void capture(int x, int y , int width , int height, String setName) {
    Robot robot = new Robot();
    Rectangle area = new Rectangle(x, y, width, height);
    BufferedImage image = robot.createScreenCapture(area);
    ImageIO.write(image, "png", new File(System.getProperty("user.dir") + "\\images\\" + setName +".png"));
}

現在機器人 class 只需獲取區域坐標並捕獲圖像,無論目標應用程序是否在頂部,為了讓應用程序位於頂部,我正在使用 JNA 使其聚焦

private static void bringToFocus() {
    for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
        if (desktopWindow.getTitle().contains("notepad")) {
            HWND hwnd = User32.INSTANCE.FindWindow(null, desktopWindow.getTitle());
            User32.INSTANCE.SetForegroundWindow(hwnd);
            break;
        }
    }
}

但這是一個我們只需要捕獲一個應用程序的示例,如果我們需要捕獲 10 個應用程序的屏幕截圖,我們需要將它們一個一個地帶到前面,然后捕獲並帶到下一個。

是否有任何可用的框架特定方法可以截取應用程序屏幕截圖而無需將其帶到前面。

如果您的屏幕截圖只需要是 Java GUI,您可以繪制到 BufferedImage

public static Image screenShot(Component c) {
  BufferedImage im = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
  Graphics g = im.getGraphics();
  c.paint(g); // Paint is the proper entry point to painting a (J)Component, rather than paintComponent
  g.dispose(); // You should dispose of your graphics object after you've finished
  return im;
}

如果您的要求是繪制 Java GUI 組件以及屏幕的 rest,但就像您的 java (J)Frame 在前面一樣,您可以先使用機器人繪制屏幕,然后執行我發布的操作上面,但是 BufferedImage(已經繪制)作為參數傳入,而不是在方法中創建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM