在Java 1.4中,您可以使用((SunToolkit)Toolkit.getDefaultToolkit()).getNativeWindowHandleFromComponent()但已删除.
看起来您现在必须使用JNI来执行此操作.您是否有JNI代码和示例Java代码来执行此操作?
我需要这个来调用Win32 GetWindowLong和SetWindowLong API调用,这可以通过Jawin库完成.
我想要一些非常精确的东西,所以我可以传递对JDialog或JFrame的引用并获取窗口句柄.
使用JNI的Swing透明度可能是相关的.
您没有编写任何C/JNI代码.来自Java:
import sun.awt.windows.WComponentPeer; public static long getHWnd(Frame f) { return f.getPeer() != null ? ((WComponentPeer) f.getPeer()).getHWnd() : 0; }
注意事项:
这使用sun.*包.显然这不是公共API.但它不太可能改变(我认为打破的可能性不如上述解决方案).
这将仅在Windows上编译和运行.您需要将其转换为反射代码,以便可移植.
这个小JNI方法接受一个窗口标题并返回相应的窗口句柄.
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; }
更新:
使用JNA,它更容易一些.我做了一个小例子,找到句柄并使用它将程序带到前面.
以下代码允许您传递Component以获取它的窗口句柄(HWND).要确保Component具有相应的窗口句柄,请在Component上调用isLightWeight()并验证它是否等于false.如果没有,请通过调用Component.getParent()来尝试它的父级.
Java代码:
package win32; public class Win32 { public static native int getWindowHandle(Component c); }
头文件main.h:
/* DO NOT EDIT THIS FILE - it is machine generated */ #include/* Header for class win32_Win32 */ #ifndef _Included_win32_Win32 #define _Included_win32_Win32 #ifdef __cplusplus extern "C" { #endif /* * Class: win32_Win32 * Method: getWindowHandle * Signature: (Ljava/awt/Component;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_win32_Win32_getWindowHandle (JNIEnv *, jclass, jobject); #ifdef __cplusplus } #endif #endif
C源main.c:
#include#include #include #include HMODULE _hAWT = 0; JNIEXPORT jint JNICALL Java_win32_Win32_getWindowHandle (JNIEnv * env, jclass cls, jobject comp) { HWND hWnd = 0; typedef jboolean (JNICALL *PJAWT_GETAWT)(JNIEnv*, JAWT*); JAWT awt; JAWT_DrawingSurface* ds; JAWT_DrawingSurfaceInfo* dsi; JAWT_Win32DrawingSurfaceInfo* dsi_win; jboolean result; jint lock; //Load AWT Library if(!_hAWT) //for Java 1.4 _hAWT = LoadLibrary("jawt.dll"); if(!_hAWT) //for Java 1.3 _hAWT = LoadLibrary("awt.dll"); if(_hAWT) { PJAWT_GETAWT JAWT_GetAWT = (PJAWT_GETAWT)GetProcAddress(_hAWT, "_JAWT_GetAWT@8"); if(JAWT_GetAWT) { awt.version = JAWT_VERSION_1_4; // Init here with JAWT_VERSION_1_3 or JAWT_VERSION_1_4 //Get AWT API Interface result = JAWT_GetAWT(env, &awt); if(result != JNI_FALSE) { ds = awt.GetDrawingSurface(env, comp); if(ds != NULL) { lock = ds->Lock(ds); if((lock & JAWT_LOCK_ERROR) == 0) { dsi = ds->GetDrawingSurfaceInfo(ds); if(dsi) { dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; if(dsi_win) { hWnd = dsi_win->hwnd; } else { hWnd = (HWND) -1; } ds->FreeDrawingSurfaceInfo(dsi); } else { hWnd = (HWND) -2; } ds->Unlock(ds); } else { hWnd = (HWND) -3; } awt.FreeDrawingSurface(ds); } else { hWnd = (HWND) -4; } } else { hWnd = (HWND) -5; } } else { hWnd = (HWND) -6; } } else { hWnd = (HWND) -7; } return (jint)hWnd; }