visual studio – MessageBox Hides the Parent Window Under Other Open Windows When Closing in WPF/Winform Application


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 MessageBox in the Window.Closing event handler
  • The Parent Window sets itself as the Owner of the Child Window

And you do this before closing the child window:

  1. Focus on any program that is behind your program, so that it is now in front of your app
  2. 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();
}

Leave a Reply

Your email address will not be published. Required fields are marked *