Main window disappears behind other application's windows after a sub window uses ShowDialog on a third window
c#, dialog, modal-dialog, window, wpf
Solution
This is a pretty annoying WPF bug, I never did find the flaw in the code that causes it but there's a heckofalot of "gotta figure this out" comments in the source code that deals with focusing. Just a workaround, a less than ideal one, you can solve it by explicitly giving the focus to the owner when the window is closing. Copy/paste this code in your SubWindow class;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {
base.OnClosing(e);
if (!e.Cancel && this.Owner != null) this.Owner.Focus();
}
Problem
I have noticed this very odd behavior in a WPF application. I have a `MainWindow`, which is shown using `Show()` from `App.OnStartup`. Said `MainWindow` can open a (non-modal) `SubWindow`, also using `Show()`. `SubWindow`'s `Owner` is set to `MainWindow`. When `SubWindow` is closed, `MainWindow` is visible again (good). Some actions can cause the `SubWindow` to open a third window as a modal dialog, using `ShowDialog()` (`Owner` is set to `SubWindow`). When that modal dialog is opened and closed at least once during the lifetime of a `SubWindow`, then the weird thing happens. After closing `SubWindow`, `MainWindow` does not come into view. Instead, whatever random window is behind `MainWindow` comes into view. Can anyone explain to me why this happens, and how to fix it? It makes no difference whether the modal dialog is a normal `Window` displayed using `ShowDialog()`, or a message box shown using `MessageBox.Show()`. Here is some minimal code to reproduce this. Create a new WPF application in visual studio, and paste this into the pre-generated MainWindow.xaml.cs Then, press a key on the keyboard to open only one window, close it, behavior as expected. Press two keys, close both, then the very first window is behind Visual Studio (presumably). ``` public MainWindow() { InitializeComponent(); this.PreviewKeyDown += (sender, e) => { if (this.Owner is MainWindow) { // we're the SubWindow MessageBox.Show("I am a modal dialog"); // code below produces the exact same behavior as the message box //var dialog = new MainWindow(); //dialog.Owner = this; //dialog.ShowDialog(); } else { // we're the initial MainWindow created by App. var subWindow = new MainWindow(); subWindow.Owner = this; subWindow.Show(); } }; } ```