加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:45:33 所属栏目:百科 来源:网络整理
导读:我正在编写一个 WPF应用程序,我想使用 this library. 我可以通过使用来获取窗口的IntPtr new WindowInteropHelper(this).Handle 但这不会转换到System.Windows.Forms.IWin32Window,我需要显示这个WinForms对话框. 如何将IntPtr转换为System.Windows.Forms.IW
我正在编写一个 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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读