【问题标题】:How to set a Wpf Window as the Owner of a Winforms Form如何将 Wpf 窗口设置为 Winforms 表单的所有者
【发布时间】:2009-07-08 01:49:45
【问题描述】:

如何将 System.Windows.Window 设置为 System.Windows.Forms.Form 的所有者?

在我搜索了一段时间后才意识到我已经在我的一个实用程序类中找到了答案,我决定将答案放在 stackoverflow 上。希望有人觉得这很有用。

【问题讨论】:

    标签: c# wpf winforms


    【解决方案1】:

    使用这个方法:

    [DllImport("user32.dll")]
    
    private static extern int SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong);
    
    /// <summary>
    /// sets the owner of a System.Windows.Forms.Form to a System.Windows.Window
    /// </summary>
    /// <param name="form"></param>
    /// <param name="owner"></param>
    public static void SetOwner(System.Windows.Forms.Form form, System.Windows.Window owner)
    {
        WindowInteropHelper helper = new WindowInteropHelper(owner);
        SetWindowLong(new HandleRef(form, form.Handle), -8, helper.Handle.ToInt32());
    }
    

    【讨论】:

    • 注意要编写与 32 位和 64 位版本的 Windows 兼容的代码,请使用 SetWindowLongPtr。为 32 位 Windows 编译时,SetWindowLongPtr 定义为对 SetWindowLong 函数的调用。
    【解决方案2】:

    SetParent 不被认为比SetWindowLongGWL_HWDPARENT (-8)“更正确”吗?

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
    

    【讨论】:

    • 这对我将 WPF 窗口设置为 Win32 对话框的父级非常有用。
    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多