Java Component和win32窗口句柄的转换

来源:互联网 发布:淘宝安卓下载 编辑:程序博客网 时间:2024/05/21 10:18
 对于win32,窗口句柄HWND是一个很关键的资源,有很多的操作都需要HWND做为参数。而在Java中,是没有HWND这个概念的,所有的操作都是以Component方法调用的方式完成的。如果我们能够根据Component得到对应的Win32 HWND,也就意味着可以按windows的方式完成对Java Component的一些操作。而这可以通过Java的JNI接口实现。

实现这一功能需要用到JNI的jawt.h文件,示例代码如下:

JNIEXPORT jint JNICALL Java_getjavacomponent_Util_getWindowHandle(JNIEnv *env, jclass, jobject joComponent)
{
    JAWT awt;
    JAWT_DrawingSurface* ds;
    JAWT_DrawingSurfaceInfo* dsi;
    JAWT_Win32DrawingSurfaceInfo* dsi_win;
    jboolean result;
    jint lock;
    jint hwnd = -1;

    // Get the AWT
    awt.version = JAWT_VERSION_1_3;
    result = JAWT_GetAWT(env, &awt);
    assert(result != JNI_FALSE);

    // Get the drawing surface
    ds = awt.GetDrawingSurface(env, joComponent);
    assert(ds != NULL);

    // Lock the drawing surface
    lock = ds->Lock(ds);
    assert((lock & JAWT_LOCK_ERROR) == 0);

    // Get the drawing surface info
    dsi = ds->GetDrawingSurfaceInfo(ds);

    // Get the platform-specific drawing info
    dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;

    hwnd = (jint)(dsi_win->hwnd);

    // Free the drawing surface info
    ds->FreeDrawingSurfaceInfo(dsi);

    // Unlock the drawing surface
    ds->Unlock(ds);

    // Free the drawing surface
    awt.FreeDrawingSurface(ds);

    return hwnd;
}

jawt.h提供的另外一个方法jobject (JNICALL *GetComponent)(JNIEnv* env, void* platformInfo);可以帮助我们通过HWND得到Java Component对象。

值得注意的是:这些操作只对于Java heavyweight component有用。
原创粉丝点击