Search code examples
c#wpfxaml

How to close current window (in Code) when launching new Window


SignInWindow signIn= new SignInWindow();
signIn.ShowDialog();

The above code is in my MainWindow class.

When the new Window is shown, I want the current window to close. Whats the best way to do this?

My application is a C# WPF application


I've tries this but when it's called, my application exits

    static private void CloseAllWindows()
    {
        for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
            App.Current.Windows[intCounter].Close();
    }

Solution

  • Just do this:

    this.Close();
    SignInWindow signIn = new SignInWindow();
    signIn.ShowDialog();
    

    bear in mind that will actually close the MainWindow. If all you're really trying to do is hide it, then do this:

    this.Hide();
    SignInWindow signIn = new SignInWindow();
    signIn.ShowDialog();
    this.Show();
    

    That will hide the MainWindow while the login form is up, but then show it again when it's complete.


    Okay, so apparently you're launching this form from a static class that is outside the form. That would have been pretty relevant information. But a solution would be this:

    var w = Application.Current.Windows[0];
    w.Hide();
    
    SignInWindow signIn = new SignInWindow();
    signIn.ShowDialog();
    
    w.Show();