Close program from main constructor






Sometimes you realize in the constructor that some criteriums are not fulfilled. Maybe there is no network access or something similar. The problem is that you can’t run the normal Close() for the window.

One simple way of getting around this is to create an EventHandler for the Loaded event because when that event is being executed you can call the Close() function.

private void markProgramForCloseDuringStartup()
{
  this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
  Close();
}

Assuming you need this event for something else you can also create an internal variable keeping track on the startup success as in this example.

public MainWindow()
{
  InitializeComponent();
  this.Loaded += new RoutedEventHandler(MainWindow_Loaded);

  // Other things to do 
}

private bool closeProgramAfterStartup = false;

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
  if (closeProgramAfterStartup)
  {
    Close();
  }
}







Yet another option is of course to move away all of this sensitive code that might need to close the program into one of the startup events that runs before the window is visible.