PDA

Click to See Complete Forum and Search --> : Changing the Background of an MDI Parent Form


jmcilhinney
Oct 30th, 2008, 04:56 AM
VB version here (http://www.vbforums.com/showthread.php?t=496227).

I've posted a solution to this question many times already and it's come up again recently, so I figured a little CodeBank submission might be helpful. First, some background information:

When you set the IsMdiContainer property of a form to True, the IDE adds an MdiClient control to your form. The grey background you see is not the form but the MdiClient control. If you set the BackColor or BackgroundImage properties of the form it will have no effect because you can't see the form's background.

Now, it is actually this MdiClient control, not the form itself, that hosts the MDI child forms. If you add any controls to the parent form then they will either be behind the MdiClient and, therefore, not visible or else on top of the MdiClient and, therefore, on top of the MDI child forms too.

The developer is not intended to mess with this MdiClient control so no member variable is provided with which to access it. It's not inaccessible though, so if you want to change the visible background of the parent form you can do this:private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctl in this.Controls)
{
if (ctl is MdiClient)
{
// Set properties of ctl here, e.g.
ctl.BackgroundImage = Properties.Resources.MdiBackgroundImage;
break;
}
}
}

jmcilhinney
Jan 5th, 2009, 02:12 AM
Here's some more succinct code that uses extension methods and, therefore, requires .NET 3.5 or later:private void Form1_Load(object sender, EventArgs e)
{
// Get a reference to the first (and only) MdiClient in the Controls collection.
MdiClient client = this.Controls.OfType<MdiClient>().First();

// Set properties of the MdiClient here, e.g.
client.BackgroundImage = Properties.Resources.MdiBackgroundImage;
}