Question

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();
}
Was it helpful?

Solution

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();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top