Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for create new instance of form

Tags:

c#

winforms

I am a beginner in programming. I try to create small application with many forms. I would like to explain, how to open form with creating instance of this form with using method.

I have actually this:

    private void firtsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if(myForm == null)
        {
            myForm = new MyForm();
            myForm.MdiParent = this;
            myForm.FormClosing += myFormForm_FormClosing;
            myForm.Show();
        }
        else
        {
            myForm.Activate();
        }
    }

    void myForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        myForm = null;
    }

I want to handle many tool strip menu, and i dont want to wrtite that code in each of them, so I want to write some method for opening any form with another type.

like image 835
Igor Avatar asked Nov 28 '25 17:11

Igor


1 Answers

This allows you to display at most one MDI child form of each class:

// Stores references to form of each type:
private Dictionary<Type, Form> _childWindows = new Dictionary<Type, Form>();

private Form ShowForm<T>() where T : Form
{
    var formType = typeof(T);
    // If we already display a form of given type -> activate it
    if (_childWindows.ContainsKey(formType))
    {
        var form = _childWindows[formType];
        form.Activate();
        return form;
    }
    else
    {
        // Else create a new form instance
        var form = (Form) Activator.CreateInstance(typeof(T));
        form.MdiParent = this;
        form.FormClosing += myForm_FormClosing;
        _childWindows[formType] = form;
        form.Show();
        return form;
    }
}

void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
    _childWindows.Remove(sender.GetType());
}

Usage:

private void firtsToolStripMenuItem_Click(object sender, EventArgs e)
{
   var form = ShowForm<MyForm>();
}
like image 148
Mariusz Jamro Avatar answered Nov 30 '25 08:11

Mariusz Jamro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!