title: Main window disappears behind other application's windows after a sub window uses ShowDialog on a third window
body: <p>I have noticed this very odd behavior in a WPF application.</p>
  
  <p>I have a <code>MainWindow</code>, which is shown using <code>Show()</code> from <code>App.OnStartup</code>. Said <code>MainWindow</code> can open a (non-modal) <code>SubWindow</code>, also using <code>Show()</code>. <code>SubWindow</code>'s <code>Owner</code> is set to <code>MainWindow</code>.</p>
  
  <p>When <code>SubWindow</code> is closed, <code>MainWindow</code> is visible again (good).</p>
  
  <p>Some actions can cause the <code>SubWindow</code> to open a third window as a modal dialog, using <code>ShowDialog()</code> (<code>Owner</code> is set to <code>SubWindow</code>). When that modal dialog is opened and closed at least once during the lifetime of a <code>SubWindow</code>, then the weird thing happens.</p>
  
  <p>After closing <code>SubWindow</code>, <code>MainWindow</code> does not come into view. Instead, whatever random window is <em>behind</em> <code>MainWindow</code> comes into view. Can anyone explain to me why this happens, and how to fix it?</p>
  
  <p>It makes no difference whether the modal dialog is a normal <code>Window</code> displayed using <code>ShowDialog()</code>, or a message box shown using <code>MessageBox.Show()</code>.</p>
  
  <hr>
  
  <p>Here is some <em>minimal</em> code to reproduce this. Create a new WPF application in visual studio, and paste this into the pre-generated MainWindow.xaml.cs</p>
  
  <p>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).</p>
  
  <pre><code>public MainWindow()
  {
      InitializeComponent();
      this.PreviewKeyDown += (sender, e) =&gt;
      {
          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();
          }
      };
  }
  </code></pre>