【问题标题】:Get System.Windows.Forms.IWin32Window from WPF window从 WPF 窗口获取 System.Windows.Forms.IWin32Window
【发布时间】:2012-05-04 23:28:20
【问题描述】:

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

我可以使用 IntPtr 来获取窗口

new WindowInteropHelper(this).Handle

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

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

【问题讨论】:

    标签: c# wpf winforms


    【解决方案1】:

    选项 1

    IWin32Window 只需要一个 Handle 属性,因为您已经拥有 IntPtr,所以实现起来并不难。 Create a wrapper 实现 IWin32Window 的类:

    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(感谢 Scott Chamberlain 的评论)

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

    NativeWindow win32Parent = new NativeWindow();
    win32Parent.AssignHandle(new WindowInteropHelper(this).Handle);
    

    【讨论】:

    • 很好的答案;不过,该类可能会接受一个 Window 并处理 WindowInteropHelper 包装的第一层,所以您只需要new WindowWrapper(this) 并且您有一些东西可以作为 IWin32Window 传递。
    • .NET 并没有创建自己的类,而是在其NativeWindow 类中提供了一个类似的类。只需使用 OP 提供的函数中的句柄调用AssignHandle(IntPtr)
    • 我无法编译选项 2。我的代码...System.Windows.Forms.IWin32Window win32Window = new System.Windows.Forms.NativeWindow(); win32Window.AssignHandle(new WindowInteropHelper(this).Handle); ...导致编译错误“IWin32Window 不包含 AssignHandle 的定义”。我尝试使用 IWin32Window 的 System.Windows.Interop 版本,但它没有 NativeWindow() 方法。
    • @KarlHoaglund,感谢您收看这个。 AssignHandle 是 NativeWindow 而不是 IWin32Window 的方法。在 AssignHandle 方法可用之前,您需要强制转换为 NativeWindow 或将 win32Window 声明为 NativeWindow。我会更新答案
    • 如果我们使用Option2,我们完成后是否需要调用ReleaseHandle?我们需要以任何方式“清理”吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2017-12-05
    • 1970-01-01
    • 2017-10-18
    • 2011-08-14
    • 2010-11-19
    相关资源
    最近更新 更多