I have developed a sample WPF project.
Here is the main window's code-behind :
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 :
I have done the following actions :
Can someone please explain me why the main window has been automatically put in background and how to avoid it ? Thank you in advance for your help
Can't tell you why it's sent to background but the way to keep it in the foreground and focused is to make it the Owner of the child Window and to call Window.Focus()
method of the Parent Window when the child Window is closed...
public ChildWindow()
{
InitializeComponent();
Owner = Application.Current.MainWindow;
}
private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e)
{
if (Owner == null) return;
Owner.Focus();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With