문제

I have two forms named mdfi and form1. I want to make mdfi form a MdiContainer by code from form1. I tried the following but the programs close when I run:

private void Form1_Deactivate(object sender, EventArgs e)
{
    this.TopMost = false;
    Mdfi newMDIChild = new Mdfi();
    newMDIChild.IsMdiContainer = true;
    this.MdiParent = newMDIChild;
    newMDIChild.Show();
}
도움이 되었습니까?

해결책

Changing the main window of your app into a child window has many side effects. Winforms is forced to destroy the window because of the MdiParent assignment. That's enough to get your Application.Run() call in the Main() method to complete and that's the end of your app. You'll have to change that:

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

And you have to make sure that you now terminate when the MDI parent is closed:

    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();
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top