1

It appears that second windows are not closing. Here is what I am doing....

  • I have created a new WPF project.

  • I placed a button in the main window.

  • I put the following code in the button to launch a second window and hide the main.

    private void button1_Click(object sender, RoutedEventArgs e) { var projectWindow = new NewProjectInfo(); this.Hide(); projectWindow.Show(); } 

-The new window is a blank window with nothing on it.

-In the "close" event of the new window I put the code to show the main window again.

 private void Window_Closed(object sender, EventArgs e) { var mainWindow = new MainWindow(); mainWindow.Show(); } 
  • If I run the program and close the main window without opening the second window, the programs ends like I would like it to.

  • If I click the button on the main window, taking me to the second window, then close that window, taking me back to the main window, then close the main window the program does not end. (meaning I have to hit the stop button in visual studio to get it to end)

It's like visiting the second window leaves some kind of process running.

So, when I close the main window I can just run the:

 Application.Current.Close(); 

But is that safe? Do I run the chance of leaving something hanging? Or is there a better way to close that second window so when I close the main the program will end?

2 Answers 2

3

These lines

 var mainWindow = new MainWindow(); mainWindow.Show(); 

create a new MainWindow and show it. The original MainWindow is still hidden.

To resolve your problem, you need a reference to the original MainWindow instance.
Perhaps you could pass this reference when you build your secondary window

// Create a NewProjectInfo instance and pass this var projectWindow = new NewProjectInfo(this); this.Hide(); projectWindow.Show(); 

And in the constructor of the projectWindow, save the reference passed in a global var

var MainWindow _originalReference; public NewProjectInfo(MainWindow original) { _originalReference = original; } 

now the window close event could use the referenced window

private void Window_Closed(object sender, EventArgs e) { _originalReference.Show(); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of creating a new Main window, can you simply call Application.Current.MainWindow.Show(); in your closed event handler?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.