简体   繁体   English

如何通过函数调用mdi表单

[英]how to call mdi form by function

How do I create a function for following code so that i may not have to write the following whole code to make a form be used as MDICHILD Form. 如何创建一个跟随代码的函数,以便我可以不必编写以下整个代码来使表单用作MDICHILD表单。

Students stu = null;
    private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        if (stu == null || stu.IsDisposed)
        {
            stu = new Students();
            stu.MdiParent = this;
            stu.Show();
        }
        else
        {
            stu.Activate();
        }
    }

while I want it like this 虽然我想要这样

private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        CreateMdiChild(Students);
    }

and function should be like this 和功能应该是这样的

public void CreateMdiChild(Form form)
    {
        //expected code            
    }

You could make the method generic, eg : 您可以使方法通用,例如:

public void CreateMdiChildOrActivate<T>(ref T instance) where T : Form, new()
{
    if (instance == null || instance.IsDisposed)
    {
        instance = new T();
        instance.MdiParent = this;
        instance.Show();
    }
    else
    {
        instance.Activate();
    }
}

Usage: 用法:

private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
    CreateMdiChildOrActivate(ref this.stu);
}

EDIT : 编辑:

If you don't want to create a class field for each form, you can do in this way: 如果您不想为每个表单创建一个类字段,您可以这样做:

Create a class dictionary field containing the open form for each form-type: 创建一个包含每个表单类型的打开表单的类字典字段:

private Dictionary<Type,Form> openForms = new Dictionary<Type,Form>();

Then change the previous method to: 然后将以前的方法更改为:

public void CreateMdiChildOrActivate<T>() where T : Form, new()
{
    Form instance;
    openForms.TryGetValue(typeof(T), out instance);
    if (instance == null || instance.IsDisposed)
    {
        instance = new T();
        openForms[typeof(T)] = instance;
        instance.MdiParent = this;
        instance.Show();
    }
    else
    {
        instance.Activate();
    }
}

Now you can call it like this: 现在你可以像这样调用它:

private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
    CreateMdiChildOrActivate<Student>();
}
public void CreateMdiChild<T>(Form f) where T : Form, new()
{
    foreach (Form frm in f.MdiChildren)
    {
        if (frm.GetType() == typeof(T))
        {                        
            if (frm.WindowState == FormWindowState.Minimized)
            {
                frm.WindowState = FormWindowState.Normal;
            }
            else
            {
                frm.Activate();
            }
            return;
        }                    
    }
    T t = new T();
    t.MdiParent = f;
    t.Show();
}

Usage 用法

CreateMdiChild<MyForm>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM