2011-05-20 193 views
2

我在我的項目上有3個窗體。MDI窗體在C#父和子

  • form1是MDI控制器
  • form2form3是MDI子

如何創建form1作爲家長和form2form3兒童?

喜歡的東西老MFC的MDI接口:

enter image description here

想象form2是父,有一個按鈕。如果點擊,它必須在父表單中打開form3form1)。我如何設置?

回答

5

首先,確保Form1的IsMdiContainer設置爲true

然後實例Form 1和Form,設置Form1的是窗體2的的MdiParent:

// Form1.IsMdiContainer should be true 
Form1 form1 = new Form1(); 

// This automatically adds form2 into form1's MdiChildren collection 
Form2 form2 = new Form2(); 
form2.MdiParent = form1; 

在窗體2的代碼中,有一些像下面以處理按鈕的點擊事件實例Form3。

public class Form2 : Form { 
    // Include as data member so we only instantiate one Form3 
    Form3 _form3; 

    public Form2() { 
     InitializeComponent(); 
     Button1.Click += new EventHandler(Button1_Click); 
    } 

    private void Button1_Click(object sender, EventArgs e) { 
     if(_form3 == null) { 
      _form3 = new Form3(); 
      // Set Form3's parent to be Form1 
      _form3.MdiParent = this.MdiParent; 
     } 
    } 
} 

作爲一對夫婦筆記,這段代碼是非常快速和骯髒。像Form2和Form3的耦合(以及無用的類名稱Form1,Form2和Form3)有幾個不可取的事情。理想情況下,您可以通過從Form2引發表單容器可以掛鉤並實例化Form3的事件來分離Form2和Form3。此示例代碼旨在爲您提供方向。

4

只需告訴表單,其MdiParent是最新的形式。

form2 frm = new form2(); 
    frm.MdiParent = this; 
    frm.Show(); 
0
private void homeToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     frmHome objfrmHome = frmHome.GetChildInstance(); 
     objfrmHome.MdiParent = this; 
     objfrmHome.WindowState = FormWindowState.Maximized; 
     objfrmHome.Show(); 
     objfrmHome.BringToFront(); 
    } 

然後在表格您呼叫

private static frmHome m_SChildform; 
    public static frmHome GetChildInstance() 
    { 
     if (m_SChildform == null) //if not created yet, Create an instance 

      m_SChildform = new frmHome(); 
     return m_SChildform; //just created or created earlier.Return it 

    } 
0

試試這個功能

public void mdiChild(Form mdiParent, Form mdiChild) 
    { 
     foreach (Form frm in mdiParent.MdiChildren) 
     { 
      if (frm.Name == mdiChild.Name) 
      { 

       frm.Focus(); 
       return; 
      } 
     } 

     mdiChild.MdiParent = mdiParent; 
     mdiChild.Show(); 

    }