问题描述
我正在写一个WPF应用程序,我想使用的。
I'm writing a WPF app, and I'd like to make use of this library.
我可以得到一个的IntPtr
为窗口,通过使用
I can get an IntPtr
for the window by using
new WindowInteropHelper(this).Handle
但不会转换为 System.Windows.Forms.IWin32Window
,我需要出示此的WinForms对话框。
but that won't cast to System.Windows.Forms.IWin32Window
, which I need to show this WinForms dialog.
我如何投的IntPtr
到 System.Windows.Forms.IWin32Window
?
推荐答案
选项1
IWin32Window只需要一个处理
属性,因为你已经拥有的IntPtr这是不是太难以实施。 类,它实现IWin32Window的包装:
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;
}
您然后会得到你的IWin32Window是这样的:
You would then get your IWin32Window like this:
IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle);
或(响应KeithS'建议):
or (in response to KeithS' suggestion):
IWin32Window win32Window = new WindowWrapper(this);
选项2 (感谢斯科特张伯伦的评论)
OPTION 2 (thx to Scott Chamberlain's comment)
使用现有的NativeWindow类,它实现了IWin32Window:
Use the existing NativeWindow class, which implements IWin32Window:
IWin32Window win32Window = new NativeWindow();
win32Window.AssignHandle(new WindowInteropHelper(this).Handle);
这篇关于从WPF窗口获取System.Windows.Forms.IWin32Window的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!