private static void SetOwnerWindow(SystemWindow window, SystemWindow ownerWindow, IntPtr ownerHandle, bool forceNewOwner, bool focusFirstControl)
{
if (focusFirstControl)
{
window.FocusFirstControl();
}
if (!forceNewOwner && HasOwner(window))
{
return;
}
try
{
if (ownerWindow != null)
{
if (ReferenceEquals(ownerWindow, window))
{
Log.Warning("Cannot set owner window to itself, no owner window set");
return;
}
if (window.Dispatcher.GetThreadId() != ownerWindow.Dispatcher.GetThreadId())
{
Log.Warning("The owner window '{0}' is not created on the same thread as the current window '{1}', cannot set owner window",
ownerWindow.GetType().GetSafeFullName(false), window.GetType().GetSafeFullName(false));
return;
}
window.Owner = ownerWindow;
}
else
{
// Set owner via interop helper
var interopHelper = new WindowInteropHelper(window);
interopHelper.Owner = ownerHandle;
// Get handler (so we can nicely unsubscribe)
RoutedEventHandler onWindowLoaded = null;
onWindowLoaded = delegate(object sender, RoutedEventArgs e)
{
// Since this owner type doesn't support WindowStartupLocation.CenterOwner, do
// it manually
if (window.WindowStartupLocation == WindowStartupLocation.CenterOwner)
{
// Get the parent window rect
RECT ownerRect;
if (GetWindowRect(ownerHandle, out ownerRect))
{
// Get some additional information
int ownerWidth = ownerRect.Right - ownerRect.Left;
int ownerHeight = ownerRect.Bottom - ownerRect.Top;
int ownerHorizontalCenter = (ownerWidth / 2) + ownerRect.Left;
int ownerVerticalCenter = (ownerHeight / 2) + ownerRect.Top;
// Set the location to manual
window.WindowStartupLocation = WindowStartupLocation.Manual;
// Now we know the location of the parent, center the window
window.Left = ownerHorizontalCenter - (window.ActualWidth / 2);
window.Top = ownerVerticalCenter - (window.ActualHeight / 2);
}
}
((SystemWindow)sender).Loaded -= onWindowLoaded;
};
window.Loaded += onWindowLoaded;
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to set the owner window");
}
}