Paul Grinberg Paul Grinberg - 9 months ago 69
C# Question

Background/border of a button derived CustomControl

I have a CustomControl which derives from a Button. At certain points in this control's life, I want to set it's background to a special color (i.e. Plum) or a normal Control color (i'e same as the default color for other buttons). Here's the relevant code that mostly works.

public partial class MySpecialButton : Button
private void SetButtonState()
if (isSpecial && Enabled)
BackColor = Color.Plum;
BackColor = Enabled ? SystemColors.Control : SystemColors.ControlDark;

This has several problems:

  1. When my control is enabled and not in Special mode, the control color that the button is drawn with seems too light compared to other buttons. You can see this in the following image where the "Create Default" button is a normal button with the default color, and the "Read From Device" button is my special button with the background color set to SystemColors.Control. Why are the two colors different?
    Depiction of different back colors

  2. When my control is drawn with any background color using the code above, there seems to be a border around the button, that I don't want. For example, in the above picture, the "Read From Device" button has a rather thick border of what appears to be a Control color.

  3. When my control is drawn with the underlying Button.Enabled = false, the color is not the same color as the default color for disabled buttons. You can see that in the picture below. The color of the "Write To Device" control is too dark compared to the "Save To Computer" button, both of which have Enabled = false.
    Depiction of different disabled colors

  4. The disabled control has the wrong foreground text color. How can I leverage the base class' mechanism to properly draw the text/background/border/etc correctly?

Answer Source

Consider these notes:

  1. Setting a BackColor property of a Button cause setting UseVisualStyleBackColor to false and the difference which you see between a normal button and your custom button is because of this. To solve the problem you should set UseVisualStyleBackColor to true again, after resetting BackColor to SystemColors.Control.

  2. If you don't like that border paint the button yourself or use FlatStyle set to Flat and use FlatAppearance.BorderSize = 0 or any other appearance and border-size which you prefer.

  3. The same as number one.

  4. Foreground color of a disabled Button is calculated based on background color. So if you reset the back ground color as described in number one, you will see no difference.