Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

xaml

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();
    }
like image 613
software is fun Avatar asked Oct 08 '13 13:10

software is fun


2 Answers

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();
like image 71
Mike Perrenoud Avatar answered Oct 12 '22 09:10

Mike Perrenoud


You can try this:

SignInWindow signIn= new SignInWindow();
Application.Current.Windows[0].Close();
signIn.ShowDialog();
like image 20
DJ Dev J Avatar answered Oct 12 '22 09:10

DJ Dev J