Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# duplicate open form code redundancy

Tags:

c#

winforms

I got a code to open my forms without any duplication, but i want to create a method for this, to avoid code redundancy.

My code :

    private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        foreach (Form openForm in Application.OpenForms)
        {
            if (openForm.GetType() == typeof(form1))
            {
                openForm.Activate();
                return;
            }
        }

        form1 f1 = new form1();
        f1.MdiParent = this;
        if (!f1.IsDisposed)
            f1.Show();
    }

What i want to:

public void formOpener(Form form, string formName)
{
    foreach (Form openForm in Application.OpenForms)
    {
        if (openForm.GetType() == typeof(form))
        {
            openForm.Activate();
            return;
        }
    }

    form formName = new form();
    formName.MdiParent = this;
    if (!formName.IsDisposed)
        formName.Show();
}

private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    formOpener(form1);
}

I have some issues with the parameters. Thanks for any answer!

like image 830
David Kovacs Avatar asked Mar 11 '23 00:03

David Kovacs


1 Answers

Something like that?:

public void formOpener<T>() where T : Form, new()
{
    var openedForm = Application.OpenForms.OfType<T>().FirstOrDefault();

    if (openedForm != null)
    {
        openedForm.Activate();
        return;
    }

    T newForm = new T();
    newForm.MdiParent = this;
    newForm.Show();
}

OfType<T> extension method requires using System.Linq;

Usage

formOpener<Form1>();

This will show the form if there is any open. Otherwise, will create new one.

If you can have multiple forms of type T open, then use Name property to distinguish them.

public void formOpener<T>(string formName) where T : Form, new()
{
    var openedForm = Application.OpenForms.OfType<T>()
        .Where(x => x.Name == formName).FirstOrDefault();
}
like image 172
Orkhan Alikhanov Avatar answered Mar 25 '23 10:03

Orkhan Alikhanov