WPF main window placed in background after closing child window

I developed a sample WPF project.
Here is the main window code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;

namespace MainWindowInBackground
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window l_hostWindow = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test"
            };

            l_hostWindow.Show();

            Window l_hostWindow2 = new Window()
            {
                Owner = System.Windows.Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = "Test 2"
            };

            l_hostWindow2.Show();
            l_hostWindow2.Close();

            //MessageBox.Show(this, "MessageBox", "MessageBox", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
        }
    }
}

When the user clicks the button:

  • Window R1 is created and displayed.
  • Window R2 is created and displayed
  • Window R2 closed

I performed the following steps:

  • I launched the application. Screenshot after action:

enter image description here

  • I pressed the button. Window R1 has appeared. Screenshot after action:

enter image description here

  • I closed the window R1. The main window is automatically placed in the background. Screenshot after action:

enter image description here

Can someone explain to me why the main window was automatically placed in the background and how to avoid it? Thank you in advance for your help.

+3
source share
1 answer

, , , Window.Focus() , ...

public ChildWindow()
{
    InitializeComponent();
    Owner = Application.Current.MainWindow;
}

private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
    if (Owner == null) return;
    Owner.Focus();
}
+4

All Articles