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

后端 未结 6 731
伪装坚强ぢ
伪装坚强ぢ 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:03

    This is the same as Jared MacD's answer but it uses reflection so that the code can compile and load on a non-Windows computer. Of course it will fail if you try to call it.

    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);
    
        }
    
    
    }
    

提交回复
热议问题