views:

42

answers:

2

Best way to track multiple windows in C# WinForms.

For instance, i have an ApplicationContext thats used to manage my application and i have a method thats used to open new windows.

public void CreateWindow(RosterItem Roster)
{
   //Check if it is already active, if so, Focus.
   MessageWindow MessageWindow = new MessageWindow();
   MessageWindow.SetContext(Roster);
   MessageWindow.Initialize();
}

That being said, I need to check to see if the window is already open and if it is the make it focused, otherwise create a new window and Focus it.

Taking into consideration Cross Thread.

Q: What is the best way to accomplish this.

+1  A: 

There is an Application.OpenForms property that keeps track of open forms - not sure about its thread safety though.

Adam
+1  A: 

MSDN says that FormCollection methods are not guaranteed to be thread safe. So it makes more sense to spin your own collection that is synchronized and is appended to at the end of CreateWindow. This way you will have one location to check when you are about to make a new window. You also get the bonus of having the form typed the way want it and don't have to do any casting.

An example of how it might work, where windowCollection is a static dictionary that every thread can see:

public Form GetWindow(RosterItem roster) {
  Form result;
  lock(windowCollection) {
    if (windowCollection.TryGetValue(roster, out result))
      return result;
    result = new MyForm(roster);
    windowCollection.Add(roster, result);
    return result;
  }
}
unholysampler
So what your saying is that i should create my own collection `Key,Value` and assign a UID to each window, then use `WindowCollection[UID].Value.InvokeRequired`, would that be the best way?, I don't think I need WindowCreate as I already have the form created, and its initiated depending on the values of the Roster.
RobertPitt
I added some example code to give you an idea of the process. You can decide what you want to use for the key, but process is the same.
unholysampler
Alternatively you could wrap access to the form collection and provide your own locking. Also, if you have many separate threads how are they going to share forms?
Adam