javajavafx-2jnajavafx-8hwnd

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?


Solution

  • 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;
        }
    }