This step-by-step article describes how to programmatically
change the background color for a Multiple Document Interface (MDI) parent form
by using Microsoft Visual C++ .NET 2003 or Microsoft Visual C++
2005.
When you use a Windows form as an MDI parent form, the
Application Background color setting in Control Panel
determines the background color of the form. The color is not determined by the
BackColor property of the form.
The following steps demonstrate how to programmatically
change the background color of the MDI parent form to another color:
Start Microsoft Visual Studio .NET or Microsoft Visual
Studio 2005.
On the File menu, point to
New, and then click Project.
Under Project Types, click Visual
C++ Projects.
Note In Visual Studio 2005, click Visual C++ under
Project Types.
Under Templates, click Windows
Forms Application (.NET).
Note In Visual Studio 2005, click Windows Forms
Application under Templates.
In the Name box, type
Q816184.
In the Location box, type
C:\Test, and then click OK.
By
default, a form that is named Form1 is created.
Click the Form1 form. On the
View menu, click Properties Window to view
the properties for the form.
Set the BackColor property to the color
that you want.
Set the IsMDIContainer property to
True.
Notice that the background color of the
form changes to the color that the Application Background
color is set to in Control Panel.
Set the WindowState property to
Maximized.
On the View menu, click
Code.
Add the following code to the Load event handler of the
Form1 form:
{
MdiClient* ctlMDI;
// Loop through all the controls of the form controls looking
// for the control of type MdiClient.
IEnumerator *pEnum = this->Controls->GetEnumerator();
while(pEnum->MoveNext())
{
try
{
// Try to cast the control to type MdiClient.
System::Windows::Forms::Control *pCtrl =
__try_cast<System::Windows::Forms::Control *>(pEnum->Current);
ctlMDI = __try_cast<MdiClient*>(pCtrl);
}
catch(InvalidCastException *)
{
continue;
}
// Set the BackColor property of the MdiClient control.
ctlMDI->BackColor = this->BackColor;
break;
}
Q816184::Form2* frm = new Q816184::Form2();
frm->MdiParent = this;
frm->Show();
}
Note You must add the common language runtime support compiler option
(/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code
sample. To add the common language runtime support compiler option in
Visual C++ 2005, follow these steps:
Click Project, and then click <ProjectName> Properties. Note<ProjectName> is a placeholder for the name of the project.
Expand Configuration Properties, and
then click General.
Click to select Common Language Runtime
Support, Old Syntax (/clr:oldSyntax) in the Common Language
Runtime support project setting in the right pane, click
Apply, and then click OK.
For more information about the common language runtime
support compiler options, visit the following Microsoft Developer Network Web
site: