如何将Wpf窗口设置为Winforms窗体的所有者

12

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

我搜索了一段时间后才意识到我已经在我的工具类中找到了答案,因此我决定将答案放在 stackoverflow 上。希望有人会发现这很有用。

2个回答

12

使用这个方法:

[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());
}

4
为了编写兼容32位和64位Windows版本的代码,请使用SetWindowLongPtr。当编译32位Windows时,SetWindowLongPtr将被定义为调用SetWindowLong函数。 - Dave

7
“SetParent”比使用“SetWindowLong”和“GWL_HWDPARENT”(-8)更为准确吗?
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

这对我来说非常有效,将WPF窗口设置为Win32对话框的父级。 - SliverNinja - MSFT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接