Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从WPF窗口获取System.Windows.Forms.iwin32窗口_C#_Wpf_Winforms - Fatal编程技术网

C# 从WPF窗口获取System.Windows.Forms.iwin32窗口

C# 从WPF窗口获取System.Windows.Forms.iwin32窗口,c#,wpf,winforms,C#,Wpf,Winforms,我正在编写一个WPF应用程序,我想利用 我可以通过使用获取窗口的IntPtr new WindowInteropHelper(this).Handle 但这不会强制转换到System.Windows.Forms.IWin32Window,我需要显示此WinForms对话框 如何将IntPtr转换为System.Windows.Forms.IWin32Window?选项1 IWin32Window只需要一个句柄属性,这并不难实现,因为您已经有了IntPtr。实现IWin32Window的类: p

我正在编写一个WPF应用程序,我想利用

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

new WindowInteropHelper(this).Handle
但这不会强制转换到
System.Windows.Forms.IWin32Window
,我需要显示此WinForms对话框


如何将
IntPtr
转换为
System.Windows.Forms.IWin32Window

选项1

IWin32Window只需要一个
句柄
属性,这并不难实现,因为您已经有了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;
}
NativeWindow win32Parent = new NativeWindow();
win32Parent.AssignHandle(new WindowInteropHelper(this).Handle);
然后,您将获得如下所示的iwin32窗口:

IWin32Window win32Window = new WindowWrapper(new WindowInteropHelper(this).Handle);
或者(根据基思的建议):

选项2(感谢斯科特·张伯伦的评论)

使用现有的NativeWindow类,它实现了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;
}
NativeWindow win32Parent = new NativeWindow();
win32Parent.AssignHandle(new WindowInteropHelper(this).Handle);

伟大的回答;不过,该类可能会接受一个窗口并处理WindowInteropHelper包装的第一层,因此您只需
新建WindowWrapper(this)
,您就可以将一些内容作为IWin32Window传入。NET提供了一个类似的类,而不是创建自己的类。只需使用OP提供的函数的句柄进行调用。我无法获得选项2进行编译。我的代码<代码>System.Windows.Forms.IWin32Window win32Window=new System.Windows.Forms.NativeWindow();win32Window.AssignHandle(新的WindowInteropHelper(this.Handle))…导致编译错误“IWin32Window不包含AssignHandle的定义”。我尝试使用System.Windows.Interop版本的IWin32Window,但它没有NativeWindow()方法。@KarlHoaglund,感谢您捕捉到这一点
AssignHandle
是NativeWindow而不是IWin32Window的方法。在AssignHandle方法可用之前,您需要强制转换到NativeWindow或将
win32Window
声明为NativeWindow。我会更新答案如果我们使用选项2,完成后是否需要调用ReleaseHandle?我们需要以任何方式“清理”吗?