Open the form if there is no other instance. Open - Pass Type to Method

I want to simplify some of my codes. So I want to make a function that checks if a certain form is already open. Right now I have a code below each button in my initial form.

private void button_parts_Click(object sender, EventArgs e)
{
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm is frm_parts) { return; }
    }
    frm_Teile newForm = new frm_parts();
    newForm.Show();
}

Now I would like to have something like:

private void button_parts_Click(object sender, EventArgs e)
{
    StartNewForm(frm_parts);
}

private void StartNewForm(Type myForm)
{
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm is myForm) { return; }
    }
    myForm newForm = new myForm();
    newForm.Show();
}

But I can’t pass the type of the EDIT function : you can, of course, but I didn’t know how and where to start.

Is there a (more) way to get what I need?

+3
source share
2 answers

You can use any of these options.

Using the general method:

private void StartNewForm<T>()
    where T : Form, new()
{
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm is T) { return; }
    }
    var newForm = new T();
    newForm.Show();
}

Here is the usage: StartNewForm<Form1>();

Create your form using Activator.CreateInstance

private void StartNewForm(Type myForm)
{
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm.GetType() == myForm) { return; }
    }
    var newForm = (Form)Activator.CreateInstance(myForm);
    newForm.Show();
}

Here is the usage: StartNewForm(typeof(Form1));

Note:

  • , , , Type. , , , , , , myForm Form.

  • , , , :

    private void StartNewForm<T>() where T : Form, new()
    {
        var f = (Application.OpenForms.OfType<T>().FirstOrDefault() ?? new T());
        f.Show();
    }
    
+6

:

  • - , . , . IOnlyOnceForm - .
  • , . , , , .Show() . MySuperDuperAppFormBase ( !)
  • Application.OpenForms.OfType .
0

Source: https://habr.com/ru/post/1656098/


All Articles