/// <summary>
/// 根据子窗体自动获取父类窗体,并建立父子关系
/// </summary>
/// <param name="window">子窗体</param>
public static void SetOwner(System.Windows.Window childWindow)
{
Action defaultSetOwner = new Action(() =>
{
IntPtr parentHandler = Process.GetCurrentProcess().MainWindowHandle;
SetOwner(childWindow, parentHandler);
});
try
{
var hwnd = GetForegroundWindow();
if (hwnd != null)
{
var source = HwndSource.FromHwnd(hwnd);
if (null != source)
{
///WPF窗体
var wnd = (System.Windows.Window)source.RootVisual;
childWindow.Owner = wnd;
childWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
}
else
{
///非WPF窗体
defaultSetOwner();
}
}
else
{
defaultSetOwner();
}
}
catch (Exception)
{
defaultSetOwner();
}
}