views:

874

answers:

3

Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened? Thanks.

+2  A: 

AFAIK there is no standard way. You'll have to implement it yourself. I'd do it this way:

class TheForm: Form
{
    private static TheForm Instance;

    private TheForm() // Constructor is private
    {
    }

    public static Show(Form mdiParent)
    {
        if ( Instance == null )
        {
            // Create new form, assign it to Instance
        }
        else
            Instance.Activate(); // Not sure about this line, find the appropriate equivalent yourself.
    }

    protected override OnFormClose(EventArgs e)
    {
        Instance = null;
        base.OnFormClose(e);
    }
}

If thread safety is of concern, add the appropriate locks.

Vilx-
Thread safety should not be a problem, since you only access GUI controls from a single thread.
Groo
you could have added that this is an implementation of the singleton pattern. I prefer Fredrik Mörk's solution, it does not violate SOC
Johannes Rudolph
+6  A: 

You can interate over the OpenForms collection to check if there is already a form of the given type:

foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(MyFormType))
    {
        form.Activate();
        return;
    }
}

Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
Fredrik Mörk