(转)Single Instance Form in a MDI application

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();
}
View Code
OpenForm<NewForm>();
View Code

 另外的一种写法:

 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;
      }
   }
View Code

 

posted @ 2013-12-12 11:30  海上浪子  阅读(194)  评论(0编辑  收藏  举报