微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 从WPF窗口获取System.Windows.Forms.IWin32Window

我正在编写一个 WPF应用程序,我想使用 this library.

我可以通过使用来获取窗口的IntPtr

new WindowInteropHelper(this).Handle

但这不会转换到System.Windows.Forms.IWin32Window,我需要显示这个WinForms对话框.

如何将IntPtr转换为System.Windows.Forms.IWin32Window?

解决方法

选项1

IWin32Window只需要一个Handle属性,这不是很难实现,因为你已经有了IntPtr.实现IWin32Window的Create a wrapper类:

public class WindowWrapper : System.Windows.Forms.IWin32Window
{
    public WindowWrapper(IntPtr handle)
    {
        _hwnd = handle;
    }

    public WindowWrapper(Window window)
    {
        _hwnd = new WindowInteropHelper(window).Handle;
    }

    public IntPtr Handle
    {
        get { return _hwnd; }
    }

    private IntPtr _hwnd;
}

你会得到你的IWin32Window这样:

IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle);

或(作为回应KeithS的建议):

IWin32Window win32Window = new WindowWrapper(this);

选项2(thx to Scott ChAmberlain的评论)

使用现有的NativeWindow类,它实现了IWin32Window:

IWin32Window win32Window = new NativeWindow(); 
win32Window.AssignHandle(new WindowInteropHelper(this).Handle);

原文地址:https://www.jb51.cc/csharp/93798.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐