6

I have an application in which I will have to get at another WPF window which is open. In WinForms, I was able to use:

MainWindow main = (MainWindow)Application.OpenForms["MainWindow"];

To be able to access the the form. Now in WPF it does not exist. I have seen the other post on this site which is relevant, however it uses Application.Window which is not contained in the call. I just have :

  • Current
  • Equals
  • GetContentStream
  • GetCookie
  • GetRemoteStream
  • GetResourceStream
  • LoadComponet
  • RefrenceEquals
  • ResourceAssembly
  • SetCookie

So my question is this, is there a different version for OpenForms, or is there just a different way to go about it.

Community
  • 1
  • 1
Jacob Saylor
  • 2,371
  • 1
  • 31
  • 46

3 Answers3

4

Try looking at: Application.Current. More specifically, Application.Current.Windows.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Thanks for the answer. Would you know how to implement it using a window name vs. a index? – Jacob Saylor May 20 '10 at 22:40
  • 6
    I would use LINQ: `Application.Current.Windows.OfType().Where(x => x.Name == "MainWindow").FirstOrDefault()`, which will return a window named "MainWindow" or `null` if no such window is found. – Stephen Cleary May 20 '10 at 22:46
0
Window2 wndw = new Window2();
wndw.Owner = this;

foreach (Window w in Application.Current.Windows)
{
    if (w.Name == wndw.Name)
    {
        if (w.IsActive)
        {
            w.Focus();
            return;
        }
        else
        {
            w.Show();
            return;
        }
    }
}
Josef
  • 2,869
  • 2
  • 22
  • 23
-1

I might be late here but just in case someone needs this. If Application.OpenForms is missing on your side, that's because you have to use System.Windows.Forms.Application.OpenForms

For example:

FormCollection fc = System.Windows.Forms.Application.OpenForms;

The fc object contains properties as: Count and InnerList(very useful)

Hope it helps, even if it is 2021, I thought that someone would need this information (I haven't seen it anywhere when I searched for it)

help-info.de
  • 6,695
  • 16
  • 39
  • 41
Ana Pop
  • 19
  • 1