如何在JavaFX中获取舞台的窗口句柄(hWnd)?

我们正在Windows中构建JavaFX应用程序,我们希望能够做一些事情来操纵我们的应用程序在Windows 7/8任务栏中的显示方式。 这需要修改名为“ 应用程序用户模型ID ”的Windows变量。

我们已经通过使用JNA设法完成了我们想要的Swing,我们想在JavaFX中重复我们的解决方案。 不幸的是,要做到这一点,我们需要能够为我们的应用程序中的每个窗口检索hWnd (窗口句柄)。 这可以通过JNA Native.getWindowPointer()方法在Swing / AWT中完成,该方法适用于java.awt.Window ,但我无法找到一个使用javafx.stage.Window执行此操作的好方法。

有没有人知道有什么方法可以获得hWnd Stage

这是一个JavaFX2版本(使用Stage而不是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; } } 

以下方法显示如何获取JavaFX Stage(或Window )的本机窗口句柄(hWnd),然后将其存储在JNA Pointer对象中:

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

这个解决方案很脆弱,通常是不受欢迎的,因为它使用reflection来访问一堆私有方法。 但它完成了工作。 希望Oracle最终会让我们直接访问本机窗口句柄,所以我们不必这样做。

当然,此代码仅在您在MS Windows上运行时才有效。 此外,我只是尝试使用早期版本的JavaFX 8(但我怀疑它在JavaFX 2上也能正常工作。编辑:看起来它在JavaFX 2中不起作用。)

 com.sun.glass.ui.Window.getWindows.get(0).getNativeWindow 

//

 com.sun.glass.ui.Window.getFocusedWindow.getNativeWindow