18

I have a button on a Windows Forms form for which I change the background color to Color.Yellow when it's clicked. When it's clicked again I want to restore it to the original default appearance.

The default backcolor is SystemColor.Control.

When the button is clicked the first time the only thing I change is the

btn.Text = "ABC";
btn.BackColor = Color.Yellow;

When it's clicked again I do

btn.BackColor = SystemColors.Control

The new background does not have the same shading as it originally did before any clicks. The button originally had a background that was not a solid color, but was two slightly different shades of grey. The final color ends up being a solid shade of grey.

I'm testing this on a Windows 7 machine.

Screenshot:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JonF
  • 2,336
  • 6
  • 38
  • 57

4 Answers4

24

Try this:

if (button1.BackColor == Color.Yellow)
{
    button1.BackColor = SystemColors.Control;
    button1.UseVisualStyleBackColor = true;
}
else
{
    button1.BackColor = Color.Yellow;
}
mj82
  • 5,193
  • 7
  • 31
  • 39
12

You should also set UseVisualStyleBackColor to true. This property gets set to false when you change the backcolor.

Arno Kalkman
  • 183
  • 5
3

Try using btn.ResetBackColor() instead of manually setting the BackColor.

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
Marty
  • 7,464
  • 1
  • 31
  • 52
  • 1
    That function doesn't exist in the winform button (at least in a .net 3.5 winform) – JonF Nov 21 '11 at 20:38
  • 3
    It actually does exist, it just doesn't show up in intellisense because it's marked as [EditorBrowsable(EditorBrowsableState.Never)] – Marty Nov 21 '11 at 20:40
  • 1
    @JonF According to [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resetbackcolor.aspx) it exists, since .Net 1.0 – Nasreddine Nov 21 '11 at 20:41
  • My bad. Unfortunately I get the same result with that – JonF Nov 21 '11 at 20:50
1

This will restore the default look (tested on Windows 7, .net 3.5):

btn.BackColor = System.Drawing.Color.Transparent; 
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Nenad
  • 11
  • 2