NoCtrlZ

GetWindowRect

Sep 8th, 2021 (edited)
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.util.Arrays;
  2. import com.sun.jna.*;
  3. import com.sun.jna.platform.win32.WinDef.HWND;
  4. import com.sun.jna.win32.*;
  5.  
  6. public class GetWindowRect {
  7.  
  8.     public interface User32 extends StdCallLibrary {
  9.         User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
  10.                 W32APIOptions.DEFAULT_OPTIONS);
  11.  
  12.         HWND FindWindow(String lpClassName, String lpWindowName);
  13.  
  14.         int GetWindowRect(HWND handle, int[] rect);
  15.     }
  16.  
  17.     public static int[] getRect(String windowName) throws WindowNotFoundException,
  18.             GetWindowRectException {
  19.         HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
  20.         if (hwnd == null) {
  21.             throw new WindowNotFoundException("", windowName);
  22.         }
  23.  
  24.         int[] rect = {0, 0, 0, 0};
  25.         int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
  26.         if (result == 0) {
  27.             throw new GetWindowRectException(windowName);
  28.         }
  29.         return rect;
  30.     }
  31.  
  32.     @SuppressWarnings("serial")
  33.     public static class WindowNotFoundException extends Exception {
  34.         public WindowNotFoundException(String className, String windowName) {
  35.             super(String.format("Window null for className: %s; windowName: %s",
  36.                     className, windowName));
  37.         }
  38.     }
  39.  
  40.     @SuppressWarnings("serial")
  41.     public static class GetWindowRectException extends Exception {
  42.         public GetWindowRectException(String windowName) {
  43.             super("Window Rect not found for " + windowName);
  44.         }
  45.     }
  46.  
  47.     public static int[] getPosition(String windowName){
  48.         int[] rect;
  49.         try {
  50.             rect = GetWindowRect.getRect(windowName);
  51.             return new int[] { rect[0], rect[1] };
  52.         } catch (GetWindowRect.WindowNotFoundException e) {
  53.             e.printStackTrace();
  54.             return null;
  55.         } catch (GetWindowRect.GetWindowRectException e) {
  56.             e.printStackTrace();
  57.             return null;
  58.         }
  59.     }
  60. }
Add Comment
Please, Sign In to add comment