Search code examples
c#wpfxamlwindow

Avoid opening same window twice WPF


I'm writing a program using WPF(C#). I use method like this to open and close windows:

public static void openCloseWindow(Window toBeOpen, Window toBeClose)
{
    toBeOpen.Show();

    makeWindowCenter(toBeOpen);

    toBeClose.Close();
}

In part of program I use this method like this:

openCloseWindow(new BestCustomerWindow,this);

so it is possible to end-user click several times on a button and many windows can open.

is there any way to avoid opening a windows while it is running?

for more information:

lets I click on a button which is open window1. I want to:

  • if window1 is closed, open it.
  • else if window1 is opened, focus on window1.

Solution

  • Replace WINDOWNAME with the name of the desired Window:

    bool isWindowOpen = false;
    
    foreach (Window w in Application.Current.Windows)
    {
        if (w is WINDOWNAME)
        {
            isWindowOpen = true;
            w.Activate();
        }
    }
    
    if (!isWindowOpen)
    {
        WINDOWNAME newwindow = new WINDOWNAME();
        newwindow.Show();
    }