Search code examples
c#winforms

Change TextColor of disabled button (failed after following suggested answer)


After reading this post: Change TextColor of disabled control I follow Hans Olsson answer: "However, if you want to do it properly you need to make them Owner-draw or override the OnPaint event and draw the text yourself." So I write the function:

    private void button_resetRelay3_Paint(object sender, PaintEventArgs e)
{
    Debug.WriteLine("button_resetRelay3_Paint");
    if (true == comboBox_F3OnOffParam.Text.ToUpper().Equals("ON"))
    {
        button_setRelay3.ForeColor = Color.White;
        Debug.WriteLine("Color.White");
    }
    else
    {
        button_setRelay3.ForeColor = System.Drawing.SystemColors.ControlText;
        Debug.WriteLine("Color.ControlText");
    }
}

Despite that I always have the forecolor as gray despite the "Debug.WriteLine("Color.White");" is correctly displayed... Note: the button is Disable. No problem to change color when the button is Enable.

Do you have any suggestion?


Solution

  • Here's a lightweight extended class that uses ControlPaint.DrawButton to render the blank button so that you can cleanly draw the colored text over it.

    disabled button demo

    protected override void OnPaint(PaintEventArgs e)
    {
        if (Enabled)
        {
            base.OnPaint(e);
        }
        else
        {
            var buttonState = Enabled ? ButtonState.Normal : ButtonState.Inactive;
            ControlPaint.DrawButton(e.Graphics, ClientRectangle, buttonState);
    
            Color textColorWithTransparency = 
                Color.FromArgb(
                    0xA0,                   
                    ForeColorDisabled);
                    
            using (var brush = new SolidBrush(textColorWithTransparency))
            {
                e.Graphics.DrawString(
                    Text,
                    Font,
                    brush,
                    ClientRectangle,
                    new StringFormat
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center
                    });
            }
        }
    }
    

    You can set the disabled fore color in the designer:

    designer


    You will want to manually change instances of Button in the designer to instances of ButtonEx.

    designer