2009-10-12 352 views

回答

32

可以interate在OpenForms收集,以檢查是否已經存在給定類型的一種形式:

foreach (Form form in Application.OpenForms) 
{ 
    if (form.GetType() == typeof(MyFormType)) 
    { 
     form.Activate(); 
     return; 
    } 
} 

Form newForm = new MyFormType(); 
newForm.MdiParent = this; 
newForm.Show(); 
+0

而不是form.Activate()使用form.WindowState = FormWindowState.Normal;與前者不同,即使窗口最小化,後者也可以工作。 – docesam 2014-08-13 18:12:34

3

AFAIK是沒有標準的方式。你必須自己實現它。我會這樣做:

class TheForm: Form 
{ 
    private static TheForm Instance; 

    private TheForm() // Constructor is private 
    { 
    } 

    public static Show(Form mdiParent) 
    { 
     if (Instance == null) 
     { 
      // Create new form, assign it to Instance 
     } 
     else 
      Instance.Activate(); // Not sure about this line, find the appropriate equivalent yourself. 
    } 

    protected override OnFormClose(EventArgs e) 
    { 
     Instance = null; 
     base.OnFormClose(e); 
    } 
} 

如果需要考慮線程安全性,請添加相應的lock s。

+0

線程安全不應該是一個問題,因爲你只從單個線程訪問GUI控件。 – Groo 2009-10-12 10:18:18

+0

你可以補充說這是一個單例模式的實現。我更喜歡FredrikMörk的解決方案,它不違反SOC – 2009-10-12 12:01:59

1

此代碼工作

private void openToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     foreach (Form form in Application.OpenForms) 
     { 


      if (form.GetType() == typeof(Form2)) 
      { 
       form.Activate(); 
       return; 
      } 
     } 

     Form2 newForm = new Form2(); 
     newForm.MdiParent = this; 
     newForm.Show(); 
    } 
0

雖然這個職位是很老了,我想這將增加一個幫助。

如果表格最小化也需要處理。下面是完整的例子:

foreach (Form form in this.MdiChildren) 
{ 
    if (form.GetType() == typeof(frmMain)) 
    { 
     if (form.WindowState == FormWindowState.Minimized) 
     { 
      form.WindowState = FormWindowState.Normal; 
     } 
     form.Activate(); 
     return; 
    } 
} 
Form frm = new frmMain(); 
frm.MdiParent = this; 
frm.Show(); 
0

在vb.net我這個代碼工作

For Each f As Form In Application.OpenForms If TypeOf f Is form_name Then f.Activate() f.WindowState = FormWindowState.Normal f.StartPosition = FormStartPosition.WindowsDefaultLocation f.WindowState = FormWindowState.Maximized

  Return 
     End If  
    Next 
    form_name .MdiParent = Me 
    form_name .Show()