Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the window handle (hWnd) for a Stage in JavaFX?

We're building a JavaFX application in Windows, and we want to be able to do some things to manipulate how our application appears in the Windows 7/8 taskbar. This requires modifying a Windows variable called the "Application User Model ID".

We've already managed to do exactly what we want in Swing by using JNA, and we'd like to repeat our solution in JavaFX. Unfortunately, to do this, we need to be able to retrieve the hWnd (window handle) for each window in our application. This can be done in Swing/AWT via the JNA Native.getWindowPointer() method, which works with java.awt.Window, but I can't figure out a good way to do this with a javafx.stage.Window.

Does anyone know of any way to do get hWnd for a Stage?

like image 525
Xanatos Avatar asked Feb 22 '13 22:02

Xanatos


2 Answers

Here's a JavaFX2 version (uses Stage rather than Window):

private static Pointer getWindowPointer(Stage stage) {
    try {
        TKStage tkStage = stage.impl_getPeer();
        Method getPlatformWindow = tkStage.getClass().getDeclaredMethod("getPlatformWindow" );
        getPlatformWindow.setAccessible(true);
        Object platformWindow = getPlatformWindow.invoke(tkStage);
        Method getNativeHandle = platformWindow.getClass().getMethod( "getNativeHandle" );
        getNativeHandle.setAccessible(true);
        Object nativeHandle = getNativeHandle.invoke(platformWindow);
        return new Pointer((Long) nativeHandle);
    } catch (Throwable e) {
        System.err.println("Error getting Window Pointer");
        return null;
    }
}
like image 130
Craig Day Avatar answered Nov 03 '22 01:11

Craig Day


Add a dependency on JNA:

<dependency>
  <groupId>net.java.dev.jna</groupId>
  <artifactId>jna-platform</artifactId>
  <version>5.3.1</version>
</dependency>

Then give your Stage a distinct title ("MyStage" in this example), and then get the Window ID like this:

WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, "MyStage");

long wid = Pointer.nativeValue(hwnd.getPointer());

This will work on Windows regardless of JavaFX version.

like image 34
john16384 Avatar answered Nov 03 '22 00:11

john16384