Reputation: 23
I have an application which is a GUI written using Java Swing. Within the app I'm using a rest API which requires a window handle (HWND) as one of it's parameters (the API creates a JPG and displays it on the selected window. I need a way of programmatically getting the HWND of a JFrame to pass into this API, is this possible?
I have seen the following code recommended:
import sun.awt.windows.WComponentPeer;
public static long getHWnd(Frame f) {
return f.getPeer() != null ? ((WComponentPeer) f.getPeer()).getHWnd() : 0;
}
However, the getPeer() method is deprecated and the above code throws a NoSuchMethodError.
Upvotes: 0
Views: 163
Reputation: 3430
The Componenet#getPeer()
method was removed in Java 9. Unless you are using Java 8, you will have to use reflection to get the native handle. Here is an example (untested):
public static Optional<Long> getNativeHandle(Window window) {
try {
Field field = Component.class.getDeclaredField("peer");
field.setAccessible(true);
Object peer = field.get(window);
field.setAccessible(false);
if (peer == null)
return Optional.empty();
Method method = peer.getClass().getMethod("getHWnd");
long handle = (long) method.invoke(peer);
return Optional.of(handle);
} catch (Exception e) {
return Optional.empty();
}
}
Upvotes: 0