Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid opening same window twice WPF

Tags:

c#

window

wpf

xaml

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.
like image 889
Babak.Abad Avatar asked Dec 08 '22 13:12

Babak.Abad


1 Answers

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();
}
like image 159
Rhys Towey Avatar answered Dec 11 '22 08:12

Rhys Towey