Matt McManis Matt McManis - 2 months ago 14
C# Question

How to check if Window is already open? Duplicate Windows

I have a button that opens a Window.

If the button is pressed again, it opens a duplicate of the same window.

info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();


How do you check if the Window is already open, and deny a duplicate from being opened again?

I can't use info.ShowDialog(); because it disables the Main Window.

Solutions that have not worked:

Info info = new Info();

if (!info.IsActive)
{
info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}





Info info = new Info();

if (info.Visibility != Visibility.Visible)
{
info.Owner = Window.GetWindow(this);
info.Show();
}





public static bool IsWindowOpen<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
: Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}

private void buttonInfo_Click(object sender, RoutedEventArgs e)
{
if (!IsWindowOpen<Window>("Info"))
{
Info info = new Info();
info.Owner = Window.GetWindow(this);
info.Show();
}
}

Answer

You could use .IsLoaded field or bind the .ContentRendered event

Edit 1 -

Window1:

public class Window1 : Window
{
    private Info info = null;
    private Boolean IsInfoOpened = false;

    protected void OpenInfo()
    {
        if (this.IsInfoOpened) return;
        this.info = new Info();
        this.info.ContentRendered += delegate { this.IsInfoOpened = true; };
        this.info.Closed += delegate { this.IsInfoOpened = false; }
        this.info.Show();
    }
}
Comments