Subscribe

RSS Feed (xml)

Track the Visible Forms in an Application

NET does not provide any way of determining what forms are currently being displayed in an application. 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);
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail