0
votes

Lets take a simple WPF application with two Window classes. The MainWindow has a single control - button - which creates AnotherWindow instance. If an Exception happens after the creation before the main thread exits ButtonMethod scope, then the application remains running after the MainWindow is closed and disappeared.

A workaround for that is to set a new window's Owner property to the MainWindow object instance.

The app will also keeps running even without any exception throwing if there would be no w.Show() or w.Close() call after an instance of AnotherWindow is created.

Questions:

  • Where is such behaviour of WPF window threads is described?

  • What is the best practice for creating other windows with an exception possibility keeping in mind: set window's Owner, call window.Close() in some finally scope or something else?

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ButtonMethod();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void ButtonMethod()
        {
            Window w = new AnotherWindow();
            // Uncomment the line below to fix freezing at the exit.
            // w.Owner = this;
            throw new Exception("Custom user exception!");
            w.Show();
        }
    }
1

1 Answers

0
votes

To open a new window on wpf you use this code:

private void Button_Click(object sender, RoutedEventArgs e)
{
    SecondWindow w = new SecondWindow();
    w.Show();
}

And if you wish to close the one you're on is:

This.close();

You don't need the code

throw new Exception("Custom user exception!");

Because you're just making an exception which you are catching anyways, you throw an exception (typically) when you want to debug your code or to see if it's catching the right type of exceptions. I hope I helped.