3

How could I prevent opening multiple windows from a wpf application?

I need to open a window from the menu and if I click to open it again, I want the already opened window to become active.

Any suggestions?

profanis
  • 2,741
  • 3
  • 39
  • 49

2 Answers2

8

You could use the Application.Current.Windows collection for that. Just check whether this collection contains the window you are about to open and if it does, activate it, otherwise create new window and show it:

var existingWindow = Application.Current.Windows.Cast<Window>().SingleOrDefault(w => /* return "true" if 'w' is the window your are about to open */);

if (existingWindow != null) {
    existingWindow.Activate();
}
else {
    // Create and show new window
}
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71
  • 1
    What should be given after the lamda expression? – A Coder May 07 '14 at 07:16
  • I first use foreach (var w in Application.Current.Windows.Cast()) { MessageBox.Show(w.GetType().ToString()); YourWindow pp = new YourWindow(); } to get the YourWindow's type name from the MsgBox, then I put w => { return w.GetType().ToString() == "YourWindow's type name"; } in the lambda, in else I put y = new YourWindow(); y.Show(); other the same as in the answer, then success . here have the similar method http://stackoverflow.com/questions/16202101/how-do-i-know-if-a-wpf-window-is-opened – yu yang Jian Jan 25 '16 at 05:51
2

Here is one way to do it:

private Window _otherWindow;

private void OpenWindow()
{
   if (_otherWindow == null)
   {
      //Pass in a reference to this window so OtherWindow can call WindowClosed when it is closed..
      _otherWindow = new OtherWindow(this);

      _otherWindow.Show();

   }
   else
      _otherWindow.Activate();  //Or whatever the method is to bring a window to the front

}

public void WindowClosed()
{
    _otherWindow = null;
}
RQDQ
  • 15,461
  • 2
  • 32
  • 59
  • 1
    How can be the open and close in the same? We write the open in the main form and the close in the child form right? – A Coder May 07 '14 at 07:07