Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

Prevent Button from inheriting BackColor of Parent

When I have a parent control which has a BackColor other than SystemColors.Control, but I have buttons on that parent control that I want to be drawn in the system them. However, when I do not change the BackColor of the buttons, it's drawn in the color of the parent. When I change the BackColor of the button to SystemColors.Control, it isn't drawn in the Windows theme anymore.

alt text
The left version is with SystemColors.Control and the right is without changing the BackColor.

alt text
Blown up, it looks like this. Here you can see that the buttons have a solid background.

Any suggestions how I can fix this?

The effect in the image can be accomplished by creating a new .NET 2.0 WinForms project and changing the constructor of Form1 to the following:

public Form1()
{
    InitializeComponent();

    var textBox = new TextBox();
    Controls.Add(textBox);

    var button = new Button { Text = "L", Width = 23, Height = 18, Left = -1, Top = -1 };
    textBox.Controls.Add(button);

    // Disable the line below to get the default behavior
    button.BackColor = SystemColors.Control;
}

Upvotes: 3

Views: 2746

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 53699

I unforuantely only have access to Windows 7 at the moment so I can't test on XP etc. but are you calling Application.EnableVisualStyles in the Main entry point of your WinForms application?

On Windows 7 with Aero enabled the buttons do not assume the parent color if Application.EnableVisualStyles is called.

NB: You should set button.UseVisualStyleBackColor = true; and do not explicitly set the BackColor property of the button.

Upvotes: 4

Related Questions