Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c# - Open a Form if there is not another instance of it Open - Pass Type to a Method

I want to simplify some of my code. Therefore I want to make a function which checks, if a certain form is already open. Right now I have the code below behind every button on my start-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 cannot pass a type to a function EDIT: You certainly can, but I didn't know how and where to start.

Is there a(nother) way to achieve what I need?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use either of these options.

Using a generic 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:

  • The non-generic version is here just because you thought you can't do it using Type. But you should know the better option is using generic version because it performs type checking at compile time while in the non-generic version you should perform some validations, for example you should check if myForm is of type of Form.

  • I didn't change your code, but for example you can do it this way:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...