2

I´m programming a simple thing in C# and WPF. I have a MainWindow with a button. If I trigger the button it opens a secon window:

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

Naturally if I trigger the button three or four times, I have three or four windows open. I don´t want to use ShowDialog(), but I want to open my second window only once. I mean if I trigger the button and the window is already open, should nothing happen.

Thank you!

user3283415
  • 119
  • 1
  • 2
  • 12

2 Answers2

2

Make second an instance variable to the parent window class and only create a new window if it hasn't been created.

Of course you need to make sure to null the instance variable when the second window is closed.

public class ParentWindow ...
{
    private SecondWindow m_secondWindow = null;

    ....

    private void btnF4_Click(object sender, RoutedEventArgs e)
    {
        if (m_secondWindow == null)
        {
            m_secondWindow = new SecondWindow();
            m_secondWindow.Closed += SecondWindowClosed;
            m_secondWindow.Show();
        }
    }


    public void SecondWindowClosed(object sender, System.EventArgs e)
    {
        m_secondWindow = null;
    }
}    

This might be shortened to the following:

public class ParentWindow ...
{
    private SecondWindow m_secondWindow = null;

    ....

    private void btnF4_Click(object sender, RoutedEventArgs e)
    {
        if (m_secondWindow == null)
        {
            m_secondWindow = new SecondWindow();
        }

        m_secondWindow.Show();            
    }
}    

However, I'm never sure whether you can actually "reopen" a window that was closed before. If you need to initialize the window all over upon reopening, use the first code. If you can live with the window starting up showing the previous content, use the second.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • Thank you Thorsten. You are right, I can reopen the second window that was closed before. Maybe I must set the object-reference again to null. – user3283415 Mar 06 '14 at 10:23
0

Declare SecondWindow in Parent Window class instead of a method.

public class MainWindow : Window {
     SecondWindow second = new SecondWindow();

     private void btnF4_Click(object sender, RoutedEventArgs e) {
          if (!second.IsActive) {
               second.Show();
          }
     }
}

Declaring second in the method makes the second window local to the method, which means every time you click the button it will create a new instance of that class (window)

Khaaytil
  • 63
  • 2
  • 9
  • This prevents a second instance if an instance of the window is already open, but causes an exception if the window is closed and the button is pressed again. You need to use the visibility property: https://stackoverflow.com/questions/3568233/wpf-cannot-reuse-window-after-it-has-been-closed – DarkBarbarian Jul 05 '22 at 20:25