C# – How to avoid duplicate form creation in .NET Windows Forms

cmenunetwinforms

I am using .NET Windows Forms. My MDI parent form contains the menu. If click the menu the form will be displayed. Up to now no problem.

UserForm uf = new UserForm();
uf.Show();
uf.MdiParent = this;

If I click the menu again another duplicate of the form is created. How to solve this issue?

Best Answer

The cleanest way is to simply track the lifetime of the form instance. Do so by subscribing the FormClosed event. For example:

    private UserForm userFormInstance;

    private void showUserForm_Click(object sender, EventArgs e) {
        if (userFormInstance != null) {
            userFormInstance.WindowState = FormWindowState.Normal;
            userFormInstance.Focus();
        }
        else {
            userFormInstance = new UserForm();
            userFormInstance.MdiParent = this;
            userFormInstance.FormClosed += (o, ea) => userFormInstance = null;
            userFormInstance.Show();
        }
    }