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

To get the x and y position of “any other unrelated application” you’re going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you’ll need to download some code and integrate it with your Java application.

EDIT 1
I’m no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:

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();
      }      
   }
}

Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE’s build path.

Leave a Comment