Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate form creation in .NET Windows Forms?

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?

like image 818
Ayyappan Anbalagan Avatar asked Dec 05 '22 02:12

Ayyappan Anbalagan


1 Answers

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();
        }
    }
like image 69
Hans Passant Avatar answered Mar 04 '23 08:03

Hans Passant