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

后端 未结 6 739
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 09:24

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

It looks like you have to use JNI to

6条回答
  •  一生所求
    2020-11-28 10:06

    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.

提交回复
热议问题