Search code examples
c#wpfexpression-blend

prevent multiple open .XMAL windows when button pressed


guys how can I prevent the opening already open WPF window (without using the user control and not adding in to windows form) when button press event ?

I have following codes, but each time I press the button it will open WPF window according to button pressed amount.

Dose anybody know how to prevent that error Thank you,

 private void button1_Click(object sender, RoutedEventArgs e)
    {
        win2 v2 = new win2();
        v2.Show();

    }

here , when each time i click the above button it will open a window, but when its already open; if I clicked the same button it will open another window instead of focusing to the already open window.

how can I prevent that? (I'm using C# )


Solution

  •  private void button1_Click(object sender, RoutedEventArgs e)
        {
            if(!Application.Current.Windows.OfType<win2>().Any())
            {
                win2 v2 = new win2();
                v2.Show();
            }   
        }
    

    Application.Current.Windows lists all the currently open windows owned by your program. We can check if any are already open that are of the type win2, and if not, then we create a new one.