6.4 Track the Visible Forms in an Application


Problem

You want to keep track of all the forms that are currently being displayed. This is often the case if you want one form to be able to interact with another.

Solution

Create a class that holds the references to Form instances. Store the Form references using static variables .

Discussion

.NET does not provide any way of determining what forms are currently being displayed in an application. (The one exception is MDI applications, as described in recipe 6.5.) If you want to determine what forms are in existence, or what forms are displayed, or you want one form to call the methods or set the properties of another form, you'll need to keep track of form instances on your own.

One useful approach is to create a class consisting of static members . This class can track open forms using a collection, or dedicated properties. Here's an example of a class that can track two forms:

 public class OpenForms {     public static Form MainForm;     public static Form SecondaryForm; } 

Now when either the main or the secondary form is shown, it can register itself with the OpenForms class. A logical place to put this code is in the Form.Load event handler.

 private void MainForm_Load(object sender, EventArgs e) {     // Register the newly created form instance.     OpenForms.MainForm = this; } 

You can use similar code to remove the reference when the form is closed.

 private void MainForm_Unload(object sender, EventArgs e) {     // Remove the form instance.     OpenForms.MainForm = null; } 

Now another form can interact with this form through the OpenForms class. For example, here's how the main form would hide the second form:

 if (OpenForms.SecondaryForm != null) {     OpenForms.SecondaryForm.Hide(); } 

In this approach, we assume that every form is created only once. If you have a document-based application where the user can create multiple instances of the same form, you should track these forms using a collection. Here's an example with an ArrayList collection:

 public class OpenForms {     public static Form MainForm;     public static ArrayList DocForms = new ArrayList(); } 

Forms can then add themselves to the document collection as needed, as shown in the following code:

 private void DocForm_Load(object sender, EventArgs e) {     // Register the newly created form instance.     OpenForms.DocForms.Add(this); } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net