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

时间:2012-04-24 10:20:43

标签: c# wpf winforms

我正在撰写WPF应用,并且我想使用this library

我可以使用

为窗口获取IntPtr
new WindowInteropHelper(this).Handle

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

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

1 个答案:

答案 0 :(得分: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);