从WPF窗口获取System.Windows.Forms.IWin32Window

问题描述 投票:11回答:1

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

我可以通过使用获得一个IntPtr窗口

new WindowInteropHelper(this).Handle

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

我如何将IntPtr投射到System.Windows.Forms.IWin32Window

c# wpf winforms
1个回答
27
投票

选项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(对Scott Chamberlain的评论)

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

IWin32Window win32Window = new NativeWindow(); 
((NativeWindow)win32Window).AssignHandle(new WindowInteropHelper(this).Handle);
© www.soinside.com 2019 - 2024. All rights reserved.