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

后端 未结 4 2020
南旧
南旧 2020-12-17 03:17

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 require

4条回答
  •  庸人自扰
    2020-12-17 03:39

    The following method shows how you can get a native window handle (hWnd) for a JavaFX Stage (or Window) and then store it in a JNA Pointer object:

    private static Pointer getWindowPointer(javafx.stage.Window window) {
        Pointer retval = null;
        try {
            Method getPeer = window.getClass().getMethod("impl_getPeer");
            final Object tkStage = getPeer.invoke(window);
            Method getPlatformWindow = tkStage.getClass().getDeclaredMethod("getPlatformWindow");
            getPlatformWindow.setAccessible(true);
            final Object platformWindow = getPlatformWindow.invoke(tkStage);
            Method getNativeHandle = platformWindow.getClass().getMethod("getNativeHandle");
            retval = new Pointer((Long) getNativeHandle.invoke(platformWindow));
        } catch (Throwable t) {
            System.err.println("Error getting Window Pointer");
            t.printStackTrace();
        }
        return retval;
    }
    

    This solution is fragile and generally undesirable, since it uses reflection to access a bunch of private methods. But it gets the job done. Hopefully Oracle will eventually give us direct access to native window handles so we don't have to do this.

    Of course, this code only works when you're running on MS Windows. Also, I've only tried it out with early release builds of JavaFX 8 (but I suspect it will work fine on JavaFX 2 as well. EDIT: looks like it doesn't work in JavaFX 2.)

提交回复
热议问题