簡體   English   中英

如何在Java中獲取程序窗口的x和y?

[英]How to get the x and y of a program window in Java?

有沒有辦法讓我在Java中獲取窗口的X和Y值? 我讀到我將不得不使用運行時,因為Java不能直接搞亂,但是我不確定如何做到這一點。 誰能給我一些有關如何獲得此鏈接的提示?

要獲得“任何其他不相關應用程序”的x和y位置,您將不得不查詢操作系統,這意味着可能使用JNI,JNA或其他腳本實用程序,例如AutoIt(如果是Windows)。 我建議使用JNA或腳本實用程序,因為兩者都比JNI易於使用(據我有限的經驗),但是要使用它們,您需要下載一些代碼並將其與Java應用程序集成。

編輯1我不是JNA專家,但是我確實在弄弄它,這就是我要獲取某些命名窗口的窗口坐標的原因:

import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;

public class GetWindowRect {

   public interface User32 extends StdCallLibrary {
      User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
               W32APIOptions.DEFAULT_OPTIONS);

      HWND FindWindow(String lpClassName, String lpWindowName);

      int GetWindowRect(HWND handle, int[] rect);
   }

   public static int[] getRect(String windowName) throws WindowNotFoundException,
            GetWindowRectException {
      HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
      if (hwnd == null) {
         throw new WindowNotFoundException("", windowName);
      }

      int[] rect = {0, 0, 0, 0};
      int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
      if (result == 0) {
         throw new GetWindowRectException(windowName);
      }
      return rect;
   }

   @SuppressWarnings("serial")
   public static class WindowNotFoundException extends Exception {
      public WindowNotFoundException(String className, String windowName) {
         super(String.format("Window null for className: %s; windowName: %s", 
                  className, windowName));
      }
   }

   @SuppressWarnings("serial")
   public static class GetWindowRectException extends Exception {
      public GetWindowRectException(String windowName) {
         super("Window Rect not found for " + windowName);
      }
   }

   public static void main(String[] args) {
      String windowName = "Document - WordPad";
      int[] rect;
      try {
         rect = GetWindowRect.getRect(windowName);
         System.out.printf("The corner locations for the window \"%s\" are %s", 
                  windowName, Arrays.toString(rect));
      } catch (GetWindowRect.WindowNotFoundException e) {
         e.printStackTrace();
      } catch (GetWindowRect.GetWindowRectException e) {
         e.printStackTrace();
      }      
   }
}

當然,要使此方法起作用,就需要下載JNA庫並將其放在Java類路徑或IDE的構建路徑中。

在最終用戶的幫助下,這很容易做到。 只需讓他們單擊屏幕快照中的某個點即可。

例如

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

/** Getting a point of interest on the screen.
Requires the MotivatedEndUser API - sold separately. */
class GetScreenPoint {

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        final Dimension screenSize = Toolkit.getDefaultToolkit().
            getScreenSize();
        final BufferedImage screen = robot.createScreenCapture(
            new Rectangle(screenSize));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JLabel screenLabel = new JLabel(new ImageIcon(screen));
                JScrollPane screenScroll = new JScrollPane(screenLabel);
                screenScroll.setPreferredSize(new Dimension(
                    (int)(screenSize.getWidth()/2),
                    (int)(screenSize.getHeight()/2)));

                final Point pointOfInterest = new Point();

                JPanel panel = new JPanel(new BorderLayout());
                panel.add(screenScroll, BorderLayout.CENTER);

                final JLabel pointLabel = new JLabel(
                    "Click on any point in the screen shot!");
                panel.add(pointLabel, BorderLayout.SOUTH);

                screenLabel.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent me) {
                        pointOfInterest.setLocation(me.getPoint());
                        pointLabel.setText(
                            "Point: " +
                            pointOfInterest.getX() +
                            "x" +
                            pointOfInterest.getY());
                    }
                });

                JOptionPane.showMessageDialog(null, panel);

                System.out.println("Point of interest: " + pointOfInterest);
            }
        });
    }
}

典型輸出

Point of interest: java.awt.Point[x=342,y=43]
Press any key to continue . . .

這里的聚會稍晚一些,但會添加此內容以節省其他人的時間。 如果您使用的是JNA的最新版本,則WindowUtils.getAllWindows()將使此操作更容易實現。

我正在使用以下Maven位置中的最新穩定版本:

JNA平台-net.java.dev.jna:jna平台:5.2.0

JNA核心-net.java.dev.jna:jna:5.2.0

Java 8 Lambda (編輯:rect是一個占位符,需要使用final或有效的final才能在lambda中工作)

//Find IntelliJ IDEA Window
//import java.awt.Rectangle;
final Rectangle rect = new Rectangle(0, 0, 0, 0); //needs to be final or effectively final for lambda
WindowUtils.getAllWindows(true).forEach(desktopWindow -> {
    if (desktopWindow.getTitle().contains("IDEA")) {
        rect.setRect(desktopWindow.getLocAndSize());
    }
});

其他Java

//Find IntelliJ IDEA Window
Rectangle rect = null;
for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
    if (desktopWindow.getTitle().contains("IDEA")) {
         rect = desktopWindow.getLocAndSize();
    }
}

然后,可以在JPanel中繪制適合的捕獲圖像(如果寬高比不同,則將拉伸圖像)。

//import java.awt.Robot;
g2d.drawImage(new Robot().createScreenCapture(rect), 0, 0, getWidth(), getHeight(), this);

暫無
暫無

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

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