如何为mdi容器创建一个函数

时间:2012-03-18 13:06:19

标签: c# winforms mdi

如何为以下代码创建函数,以便我可以不必编写以下整个代码来使表单用作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();
  }
}

3 个答案:

答案 0 :(得分:5)

您拥有的代码没有任何问题。你可以通过一些反思使它变干:

    public Form CreateMdiChild(Type type, bool singleton) {
        if (singleton) {
            foreach (var child in this.MdiChildren) {
                if (child.GetType() == type) {
                    child.WindowState = FormWindowState.Normal;
                    child.Show();
                    child.Activate();
                    return child;
                }
            }
        }
        Form form = (Form)Activator.CreateInstance(type);
        form.MdiParent = this;
        form.Show();
        return form;
    }

用法:

 CreateMdiChild(typeof(Students), true);

答案 1 :(得分:2)

试试这个

private void CreateMdiChild<T>(ref T t) where T : Form, new()
{            
    if (t == null || t.IsDisposed)
    {
        t = new T();
        t.MdiParent = this;
        t.Show();
    }
    else
    {
        if (t.WindowState == FormWindowState.Minimized)
        {
            t.WindowState = FormWindowState.Normal;
        }
        else
        {
            t.Activate();
        }
    }
}

用法:

Students students;
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
    CreateMdiChild<Students>(ref students);
}

答案 2 :(得分:0)

将学生作为单身人士/表格使用:

public class Students: Form
{
    private static Students _Self;
    public static Students ShowOrActivate(Form parent)
    {
        if (_Self == null)
        {
            _Self = new Students();
            _Self.MdiParent = this;
            _Self.Show();
        }
        else
            _Self.Activate();
    }
}

现在用

显示表单
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
Students.ShowOrActivate(this);
}