Tuesday, March 4, 2008

How to draw a disabled control?

Recently I had to overwrite the OnPaint method of a button because I needed to draw a gradient background. My button had to display images and text. As the button should also have the disabled state where the image is gray scale I did not know how to get such an effect. After some research I found the ControlPaint class which is very useful not only in my case. It basically helps you to draw controls or part of controls such as the drop down button for a combo box and so on.
On the following picture you can see how this may look like:


The code to accomplish this is the following:
public class MyButton : Button
{
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.White, pevent.ClipRectangle);
g.DrawRectangle(new Pen(Brushes.Black), pevent.ClipRectangle);
if (Enabled)
{
if(Image != null)g.DrawImage(Image, 0, 0);
g.DrawString(Text, Font, Brushes.Black, new PointF(100, 0));
}
else
{
if(Image != null)ControlPaint.DrawImageDisabled(g, Image, 0, 0, Color.Transparent);
ControlPaint.DrawStringDisabled(g, Text, Font, Color.Transparent, new RectangleF(100, 0, 100, 20), StringFormat.GenericDefault);
}
}
}
The class ControlPaint offers also other usefull operations and you can take a look at all its members here.

2 comments:

Anonymous said...

Never knew the class existed until I saw this blog page. Very useful.

Anonymous said...

thanks, works fine :)