在Java Swing中,如何获得对窗口的Win32窗口句柄(hwnd)引用?

mec1mxoz  于 2023-05-05  发布在  Java
关注(0)|答案(6)|浏览(331)

在Java 1.4中,你可以使用((SunToolkit)Toolkit.getDefaultToolkit()).getNativeWindowHandleFromComponent(),但它被删除了。
看起来您现在必须使用JNI来执行此操作。你有JNI代码和示例Java代码来做这件事吗?
我需要它来调用Win32 GetWindowLong和SetWindowLong API调用,这可以通过Jawin库来完成。
我想要一些非常精确的东西,这样我就可以传递一个对JDialog或JFrame的引用并获取窗口句柄。
Swing transparency using JNI可能相关。

kqlmhetl

kqlmhetl1#

你不需要写任何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上编译和运行。您需要将其转换为反射代码,以便其可移植。
9avjhtql

9avjhtql2#

锁定,本次有disputes about this answer’s content正在解析。它目前不接受新的交互。

这个小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;
 }
iyfamqjs

iyfamqjs3#

下面的代码允许您传递一个Component以获取它的窗口句柄(HWND)。要确保组件具有相应的窗口句柄,请在组件上调用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 <jni.h>
/* 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<windows.h>
#include <jni.h>
#include <jawt.h>
#include <jawt_md.h>

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;

}
3pmvbmvn

3pmvbmvn4#

我发现了这个:http://jna.java.net/javadoc/com/sun/jna/Native.html#getWindowID(java.awt.Window)
JNA允许您调用本机库,而不必编写JNI本机代码。原来库本身有一个方法,它接受一个Window并产生一个int,可能是一个句柄(或指针?),希望能在所有平台上工作。

zynd9foi

zynd9foi5#

在JNA库中,我们看到在Java 5和6中使用Native AWT UnsatisfiedLinkError时运行headless,因此使用动态链接。参见https://github.com/twall/jna/blob/master/native/dispatch.c中的方法Java_com_sun_jna_Native_getWindowHandle0

kpbpu008

kpbpu0086#

这与Jared MacD的答案相同,但它使用反射,以便代码可以在非Windows计算机上编译和加载。当然,如果你试图调用它,它会失败。

import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WindowHandleGetter {
    private static final Logger log = LoggerFactory.getLogger(WindowHandleGetter.class);
    private final Frame rootFrame;

    protected WindowHandleGetter(Frame rootFrame) {
        this.rootFrame = rootFrame;
    }

    protected long getWindowId() {

        try {
            Frame frame = rootFrame;

            // The reflection code below does the same as this
            // long handle = frame.getPeer() != null ? ((WComponentPeer) frame.getPeer()).getHWnd() : 0;

            Object wComponentPeer = invokeMethod(frame, "getPeer");

            Long hwnd = (Long) invokeMethod(wComponentPeer, "getHWnd");

            return hwnd;

        } catch (Exception ex) {
            log.error("Error getting window handle");
        }

        return 0;
    }

    protected Object invokeMethod(Object o, String methodName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        Class c = o.getClass();
        for (Method m : c.getMethods()) {
            if (m.getName().equals(methodName)) {
                Object ret = m.invoke(o);
                return ret;
            }
        }
        throw new RuntimeException("Could not find method named '"+methodName+"' on class " + c);

    }

}

相关问题