MdiContainer形式没有开放

时间:2014-02-07 13:08:11

标签: c# winforms c#-2.0 mdi mdichild

我有两个名为mdfiform1的表单。我想通过mdfi中的代码使MdiContainer形成form1。我试过以下但是程序在我运行时关闭了:

private void Form1_Deactivate(object sender, EventArgs e)
{
    this.TopMost = false;
    Mdfi newMDIChild = new Mdfi();
    newMDIChild.IsMdiContainer = true;
    this.MdiParent = newMDIChild;
    newMDIChild.Show();
}

1 个答案:

答案 0 :(得分:2)

将应用程序的主窗口更改为子窗口有很多副作用。由于MdiParent赋值,Winforms被强制销毁窗口。这足以让您在Main()方法中调用Application.Run()来完成,这就是应用程序的结束。你必须改变它:

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var main = new Form1();
        main.Show();
        Application.Run();
    }

您必须确保现在在MDI父级关闭时终止:

    private void Form1_Deactivate(object sender, EventArgs e) {
        this.TopMost = false;
        var newMdiParent = new mdfi();
        newMdiParent.IsMdiContainer = true;
        this.MdiParent = newMdiParent;
        newMdiParent.FormClosed += (s, ea) => Application.Exit();
        newMdiParent.Show();
        this.Deactivate -= Form1_Deactivate;
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
        if (this.MdiParent == null) Application.Exit();
    }