Ok, so I think I’ve figured out a solution / workaround
First of, when does this behavior occur?
As far as I can tell, this happens when the following conditions are met:
- The Child Window opens a
MessageBoxin theWindow.Closingevent handler - The Parent Window sets itself as the
Ownerof the Child Window
And you do this before closing the child window:
- Focus on any program that is behind your program, so that it is now in front of your app
- Focus back to your program
Example:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
{
// Show MessageBox in Window.Closing event handler
if (MessageBox.Show("Are you sure you want to close?", "?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
e.Cancel = true;
}
private void OpenWindow_Click(object sender, RoutedEventArgs e)
{
var subwindow = new MainWindow();
subwindow.Owner = this; // <-- Set child owner
subwindow.Show();
}
}
(In this example the parent window and the child window are the same class, but it works the same when they are different classes)
Solution
The solution that works for me is to just focus on the Owner in the Window.Closing event handler:
private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure you want to close?", "?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
e.Cancel = true;
else if(Owner != null)
// Focus on the owner if it is set and the closing was not cancelled
Owner.Focus();
}