In Java Swing how do you get a Win32 window handle (hwnd) reference to a window?

Sarel Botha picture Sarel Botha · Dec 22, 2008 · Viewed 44.1k times · Source

In Java 1.4 you could use ((SunToolkit) Toolkit.getDefaultToolkit()).getNativeWindowHandleFromComponent() but that was removed.

It looks like you have to use JNI to do this now. Do you have the JNI code and sample Java code to do this?

I need this to call the Win32 GetWindowLong and SetWindowLong API calls, which can be done via the Jawin library.

I would like something very precise so I can pass a reference to the JDialog or JFrame and get the window handle.

Swing transparency using JNI may be related.

Answer

Jared MacD. picture Jared MacD. · Sep 16, 2010

You don't have write any C/JNI code. From Java:

import sun.awt.windows.WComponentPeer;

public static long getHWnd(Frame f) {
   return f.getPeer() != null ? ((WComponentPeer) f.getPeer()).getHWnd() : 0;
}

Caveats:

  • This uses a sun.* package. Obviously this is not public API. But it is unlikely to change (and I think less likely to break than the solutions above).
  • This will compile and run on Windows only. You would need to turn this into reflection code for this to be portable.