Jason Axelrod Jason Axelrod - 4 months ago 31
C# Question

Visual Studio C# Windows Forms... changing button color?

I have a form (see screenshot):

default form look

As you can see, its a pretty basic form, with a save button. I have programmed it so that if any of the text fields get changed, the "SAVE" button changes color so that its obvious that I haven't clicked save and don't forget to. Unfortunately, simply changing the BackColor of the button to red isn't enough, because its UGLY as sin.

ugly backcolor unsaved

What can I do to change the color of the button to red, but not as ugly. As you can see, the "BackColor" doesn't change the entire button, just the inner piece. The border is still the same old fashioned transparent grey.

Answer

A little bit of a LinearGradientBrush can go a long way to soften the harshness of a pure red button.

button1.ForeColor = Color.White;

Bitmap bmp = new Bitmap(button1.Width, button1.Height);
using (Graphics g = Graphics.FromImage(bmp)) {
  Rectangle r = new Rectangle(0, 0, bmp.Width, bmp.Height);
  using (LinearGradientBrush br = new LinearGradientBrush(
                                      r,
                                      Color.Red,
                                      Color.DarkRed,
                                      LinearGradientMode.Vertical)) {
      g.FillRectangle(br, r);
    }
  }

then you can just assign the image to the button's BackgroundImage property:

  button1.BackgroundImage = bmp;

Result:

enter image description here

Note: Assigning a background image will lose the mouse hover coloring of the button.