Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C#
Tip/Trick

Faded/Dimmed Button Images

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
15 Aug 2019CPOL 7.5K   2   5
Dim Windows Forms Buttons when disabled

Introduction

I noticed that the images on my buttons aren't faded/dimmed when they're disabled. Text/back color goes darker....but not the image. Of course, I Googled a solution....and it appears that many people have the problem and there were many suggestions....but all far too complex.

Using the Code

The code is very simple.

C#
//Define a general paint event
//This can be in a static class, a form, anywhere.
private void Ctrl_Paint(object sender, PaintEventArgs e)
{
    Control b = (Control)sender;
    //Paint a semi-transparent black rectangle over the button if disabled
    if (!b.Enabled)
    {
        using (SolidBrush brdim = new SolidBrush(Color.FromArgb(128, 0, 0, 0)))
        {
            e.Graphics.FillRectangle(brdim, e.ClipRectangle);
        }
    }
}

//Then just tie up the above to your control in a form load event:
ControlName.Paint += Ctrl_Paint;

A really simple solution - just paint a semi-transparent rectangle over the control....the amount of dimming can be altered by adjusting the alpha value (128 in the code above).

Points of Interest

You can have more than one event handler for each event. The above works by executing the Ctrl_Paint event after a control's 'normal' paint event...so it even works on overridden events in classes.

History

  • 15th August, 2019: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionControlPaint.DrawImageDisabled? Pin
Brad_Jones16-Aug-19 6:29
Brad_Jones16-Aug-19 6:29 
AnswerRe: ControlPaint.DrawImageDisabled? Pin
AntGamble15-Sep-19 23:12
AntGamble15-Sep-19 23:12 
PraiseThank you! Pin
Member 373058716-Aug-19 2:13
Member 373058716-Aug-19 2:13 
QuestionA screenshot would help, here's why... Pin
dandy7215-Aug-19 4:22
dandy7215-Aug-19 4:22 
AnswerRe: A screenshot would help, here's why... Pin
AntGamble15-Sep-19 23:14
AntGamble15-Sep-19 23:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.