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

我正在编写一个WPF应用程序,我想使用这个库 。

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

 new WindowInteropHelper(this).Handle 

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

如何将IntPtrSystem.Windows.Forms.IWin32Window

选项1

IWin32Window只需要一个Handle属性,因为你已经拥有了IntPtr,所以这个属性并不难实现。 创建一个实现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:

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