title: WPF: Closing a window programmatically without triggering Window_Closing()
body: <p>I'm making an application where the user can dynamically create more windows according to their needs.  The application always has <em>one</em> instance of MainWindow, and will have 0 or more instances of AuxWindow.</p>
  
  <p>Adding more AuxWindow instances works fine.  But I'm having problems closing them again programmatically (i.e. if the user wants to reduce the number of auxilliary windows).  Calling AuxWindow.Close() from the AuxWindow VM also triggers the Window_Closing() method, which starts asking the user for confirmation.</p>
  
  <p>So how do I differentiate between the user closing the window and the application doing it?  If the user closes the window, I want to ask for confirmation and then close down the whole application.  But if the application is closing the window, I just want it closed.</p>
  
  <p>Here's the Window_Closing() method in AuxWindow:</p>
  
  <pre><code>private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
      _logger.Info("Exit application initiated - closing window");
      var result = _auxWindowVM.Controller.ExitApplication(this);
      if (result == false) {
          _logger.Info("Closing application confirmed");
          e.Cancel = false;
      }
      else {
          _logger.Info("Closing application canceled");
          e.Cancel = true;
      }
  }
  </code></pre>
  
  <p>And here's the ExitApplication method being called from both MainWindow and all AuxWindow instances:</p>
  
  <pre><code>public bool ExitApplication(Window initWindow) {
      if (_exitConfirmed == false) {
          if (System.Windows.MessageBox.Show("Are you sure you want to exit?", "", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question, System.Windows.MessageBoxResult.No) == System.Windows.MessageBoxResult.Yes) {
              MainWindowVM.CurrentDateTimeUpdateTimer.Stop();
              SerialPortHandler.SerialPortCts.Cancel();
              ArgusMk2CommProtocol.QueueConsumerCts.Cancel();
              PollingHandler.PollingTimer.Stop();
              _exitConfirmed = true;
              Application.Current.Shutdown();
              return false;
          }
          else {
              return true;
          }
      }
      else {
          return false;
      }
  }
  </code></pre>