views:

1297

answers:

2

Hi all,

How can I change the BACKGROUND color of the MDI FORM in C#?

I changed it using the background color property but the color is not changed.

What should I do to perform this task?

Please help me out!!

Thanks in advance!!

+4  A: 

The actual BackGround colour of the MDI control is based on the colour in the Windows current Theme. You have to physically set the MdiClient control's background inside the WinForm.

    // #1
    foreach (Control control in this.Controls)
    {
        // #2
        MdiClient client = control as MdiClient;
        if (!(client == null))
        {
         // #3
         client.BackColor = GetYourColour();
         // 4#
         break;
        }
    }

Edit - Added comments:

  1. We need to loop through the controls in the MdiParent form to find the MdiClient control that gets added when you set the Form to be an MdiParent. Foreach is just a simple iteration of a type through a collection.

  2. We need to find the MdiClient control within the form, so to do this we cast the current control within the loop using the 'as' keyword. Using the 'as' keyword means that if the cast is invalid then the variable being set will be null. Therefore we check to see if 'client' is null. If it is, the current control in the loop is not the MdiClient control. As soon as the variable 'client' is not null, then the control we've got hold of is the MdiClient and we can set its background colour.

  3. Set the backcolour to anything you want. Just replace "GetYourColour()" with whatever colour you want, i.e. Color.White, Color.Blue, Colour.FromArgb(etc)...

  4. As there is only ever 1 MdiClient, there's no point continuing the loop as it's just a waste of processing time. Therefore we call 'break' to exit the loop.

Let me know if you want anything else explaining.

GenericTypeTea
Thanks for your reply. With the help of your coding I am now able to change the background color of MDI form.One more help I need.Since I am new to C# if possible can you just explain the coding please?Thanks a lot!!
sheetal
Sure, I'll add some comments to the code
GenericTypeTea
Thank you very much!!Very nice explanation!!Thanks a lot
sheetal
A: 

Try it: http://support.microsoft.com/kb/319465

Icebob
This is basically the same as what I posted, however it's checking for an invalid cast which is just bad? Why let it error and handle an error when you can just cast using the 'as' keyword and check for null?
GenericTypeTea
@DanD : I concur ! Sometimes I wonder who writes the documentation examples at Microsoft... probably trainees ;)
Thomas Levesque