private void OpenForm<T>() where T : Form, new() { T frm = (T)new List<Form>(this.MdiChildren).Find(f => f is T) ?? new T() { MdiParent = this }; frm.Show(); frm.Focus(); }
OpenForm<NewForm>();
另外的一种写法:
public partial class MDIForm : Form { private Child1Form mChild1Form = null; private Child2Form mChild2Form = null; public MDIForm() { InitializeComponent(); } private Form ShowOrActiveForm(Form form, Type t) { if (form == null) { form = (Form)Activator.CreateInstance(t); form.MdiParent = this; form.Show(); } else { if (form.IsDisposed) { form = (Form)Activator.CreateInstance(t); form.MdiParent = this; form.Show(); } else { form.Activate(); } } return form; } private void newToolStripButton_Click(object sender, EventArgs e) { mChild1Form = ShowOrActiveForm(mChild1Form, typeof(Child1Form)) as Child1Form; } private void openToolStripMenuItem_Click(object sender, EventArgs e) { mChild2Form = ShowOrActiveForm(mChild2Form, typeof(Child2Form)) as Child2Form; } }