/// <summary> /// Sets the owner window of a specific window. It will first try to set the owner via /// the <paramref name="ownerWindow"/>. If the <paramref name="ownerWindow"/> is not available, /// this method will use the <paramref name="ownerHandle"/> to set the parent. /// </summary> /// <param name="window">Reference to the current window.</param> /// <param name="ownerWindow">New owner window.</param> /// <param name="ownerHandle">The owner handle.</param> /// <param name="forceNewOwner">If true, the new owner will be forced. Otherwise, if the /// window currently has an owner, that owner will be respected (and thus not changed).</param> /// <param name="focusFirstControl">If true, the first control will automatically be focused.</param> 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"); } }