Get System.Windows.Forms.IWin32Window from WPF window

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I'm writing a WPF app, and I'd like to make use of this library.

I can get an IntPtr for the window by using

new WindowInteropHelper(this).Handle 

but that won't cast to System.Windows.Forms.IWin32Window, which I need to show this WinForms dialog.

How do I cast IntPtr to System.Windows.Forms.IWin32Window?

回答1:

OPTION 1

IWin32Window only expects a Handle property, which is not too difficult to implement since you already have the IntPtr. Create a wrapper class that implements 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; } 

You would then get your IWin32Window like this:

IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle); 

or (in response to KeithS' suggestion):

IWin32Window win32Window = new WindowWrapper(this); 

OPTION 2 (thx to Scott Chamberlain's comment)

Use the existing NativeWindow class, which implements IWin32Window:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!