Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 989
Sarel Botha Avatar asked Dec 22 '08 17:12

Sarel Botha


People also ask

What is HWND in Windows?

A Windows window is identified by a "window handle" ( HWND ) and is created after the CWnd object is created by a call to the Create member function of class CWnd . The window may be destroyed either by a program call or by a user's action. The window handle is stored in the window object's m_hWnd member variable.

How do I locate a window handle?

However, you can obtain the window handle by calling FindWindow() . This function retrieves a window handle based on a class name or window name. Call GetConsoleTitle() to determine the current console title. Then supply the current console title to FindWindow() .


2 Answers

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.
like image 196
Jared MacD. Avatar answered Sep 20 '22 13:09

Jared MacD.


This little JNI method accepts a window title and returns the corresponding window handle.

JNIEXPORT jint JNICALL Java_JavaHowTo_getHwnd      (JNIEnv *env, jclass obj, jstring title){  HWND hwnd = NULL;  const char *str = NULL;   str = (*env)->GetStringUTFChars(env, title, 0);  hwnd = FindWindow(NULL,str);  (*env)->ReleaseStringUTFChars(env, title, str);  return (jint) hwnd;  } 

UPDATE:

With JNA, it's a little bit easier. I made a small example which find the handle and use it to bring the program to front.

like image 24
RealHowTo Avatar answered Sep 20 '22 13:09

RealHowTo