Only Bolivian Here
Only Bolivian Here

Reputation: 36753

MDI child form seems to let the controls of the parent display on through as if it were transparent

Here's a small example:

A regular old form with a pictureBox and a button. Nothing fancy. In the button's click event:

private void button1_Click(object sender, EventArgs e)
{
    Form form = new Form();
    form.MdiParent = this;
    form.BackColor = Color.Red;

    form.WindowState = FormWindowState.Maximized;
    form.Show();
}

enter image description here

However, when I click on the button this happens:

enter image description here

The picturebox and the button are still showing, as if the child form were transparent. Any suggestions on how to change this? I want the child form to cover everything like a regular form.

Upvotes: 2

Views: 2471

Answers (1)

Hans Passant
Hans Passant

Reputation: 942119

The problem is that the MDI child windows are a child of the MDI client window. The one with the dark gray background. Any control you put on the MDI parent will have a higher Z-order and overlap the MDI client window. And thus any MDI child window. You can dock a control to an edge and Winforms will automatically shrink the MDI client window to fit the space that's left. Which is the proper thing to do for the button, put it on a panel and dock the panel. But that won't help for the image.

Winforms makes it a bit tricky to get a reference to the MDI client window, you have to iterate the MDI parent's Controls collection to find it back. Like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.IsMdiContainer = true;
        foreach (Control ctl in this.Controls) {
            if (ctl is MdiClient) {
                ctl.BackgroundImage = Properties.Resources.Chrysanthemum;
                ctl.BackgroundImageLayout = ImageLayout.Center;   // doesn't work
                break;
            }
        }
    }
}

Note the comment, fixing this is a lot harder then I counted on. Implementing the Paint event for the window is an option but it flickers like a cheap motel.

Upvotes: 3

Related Questions