user3265040
user3265040

Reputation: 315

How can I prevent WPF app from closing main window when opening a new window?

I use this method to show another window from my main window.

   public void DisplayLobbyWindow()
    {
        var d = Application.Current.Dispatcher;

        if (d.CheckAccess())
        {
            new LobbyWindow()
            {
                Owner = this
            }.Show();

            this.Close();
        }
        else
        {
            d.BeginInvoke((Action)DisplayLobbyWindow);
        }
    }

However, the main application closes when I show the new one. I don't want it to close, I just want to make the first window disappear and show the next one. How's that possible? Thanks.

EDIT: I guess it could be because the Owner property is set to the Main Window - however I need it to start up in the main window's location so I set the owner to it. Is there a workaround?

Upvotes: 1

Views: 625

Answers (1)

Grant Winney
Grant Winney

Reputation: 66509

Modify your code to hide the window. You can also specify the startup location, since you said you want the new window to pop up where the old window was.

public void DisplayLobbyWindow()
{
    ...
        new LobbyWindow()
        {
            Owner = this,
            WindowStartupLocation = WindowStartupLocation.CenterOwner
        }.Show();

        this.Hide();
    ...
}

Then in your second form, subscribe to the Closed event:

<Window x:Class="WpfApplication1.LobbyWindow"
    Title="LobbyWindow" Closed="LobbyWindow_OnClosed">

So that you can display the first form again. Otherwise, the second window will display and your app will just keep running, invisible.

 private void LobbyWindow_OnClosed(object sender, EventArgs e)
 {
     Owner.Show();
 }

Upvotes: 1

Related Questions