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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1095763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:06:15  来源:igfitidea点击:

How to set a Wpf Window as the Owner of a Winforms Form

c#wpfwinforms

提问by Patrick Klug

How to set a System.Windows.Window as the Owner of a System.Windows.Forms.Form?

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

After I searched for this for a while only to realize that I already have the answer in one of my utils classes I decided to put the answer on stackoverflow. Hopefully someone finds this useful.

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

采纳答案by Mike

Isn't SetParentconsidered "more correct" than SetWindowLongwith GWL_HWDPARENT(-8)?

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

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

回答by Patrick Klug

Use this method:

使用这个方法:

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