1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| public class WIN32GetWindow {
public static void main(String[] args) {
// pour obtenir la fenêtre en premier plan
System.out.println(WIN32GetWindow.getTopLevelWindow());
// pour obtenir la liste des fenetres (tu peux comparer le nom de la fenêtre à celle que tu cherches
/*for(Window window : WIN32GetWindow.getWindows()) {
System.out.println(window);
}*/
}
public static class Window {
private String name;
private Rectangle bounds;
private Window(String name, Rectangle bounds) {
this.name=name;
this.bounds=bounds;
}
public String getName() {
return name;
}
public Rectangle getBounds() {
return bounds;
}
@Override
public String toString() {
return String.format("[name: %s, title: %s, bounds: %s", name, bounds);
}
}
private interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);
boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
int GetWindowRect(HWND handle, int[] rect);
int GetWindowTextA(HWND hWnd, byte[] lpString, int nMaxCount);
HWND GetActiveWindow();
HWND GetForegroundWindow();
}
public static Window getActiveWindow() {
HWND hwnd = User32.INSTANCE.GetActiveWindow();
if ( hwnd==null ) {
return null;
}
return getWindow(hwnd);
}
public static Window getTopLevelWindow() {
HWND hwnd = User32.INSTANCE.GetForegroundWindow();
if ( hwnd==null ) {
return null;
}
return getWindow(hwnd);
}
private static Collection<Window> getWindows() {
final Collection<Window> windows = new ArrayList<>();
User32.INSTANCE.EnumWindows(new WNDENUMPROC() {
@Override
public boolean callback(HWND hwnd, Pointer arg1) {
String windowName = getWindowName(hwnd);
Window window = getWindow(hwnd);
if ( !window.getName().isEmpty() ) {
windows.add(new Window(windowName, getWindowBounds(hwnd)));
}
return true;
}
}, null);
return windows;
}
private static String getWindowName(HWND hwnd) {
byte[] windowText = new byte[512];
User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512);
return Native.toString(windowText);
}
private static Window getWindow(HWND hwnd) {
String windowName = getWindowName(hwnd);
return new Window(windowName, getWindowBounds(hwnd));
}
private static Rectangle getWindowBounds(HWND hwnd) {
int[] rect = { 0, 0, 0, 0 };
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
return null;
}
return new Rectangle(rect[0],rect[1],rect[2],rect[3]);
}
} |