Transparent Color in C# control: Bug fix details

| | Comments (1)

I thought it might be interesting to document the recent code modifications to CrystalGradientControl to allow sub-classes (CrystalLabel and CrystalPictureBox) to have transparent backgrounds.

As most Windows Forms programmers know, setting the BackColor to Transparent is the way to allow transparent backgrounds in most controls. I wanted to support the same convention. However, setting the BackColor to Transparent result in a nasty message ("Control does not support transparent background colors"). To fix this, I had to call SetStyles to declare that my color does support transparency:

public CrystalGradientControl()
{
  SetStyle(ControlStyles.SupportsTransparentBackColor, 
           true);
}

Next, I wanted to override the property (from the base class Control), BackColor. Why? Because when BackColor is set to Transparent, I needed to set an internal property called TransparentMode to True. TransparentMode triggers a number of things best described on Bob Powell's article on transparent controls. This was all I needed to do:

public override Color BackColor
{
    get
    {
        return base.BackColor;
    }
    set
    {
        if (base.BackColor != value)
        {
          base.BackColor = value;
          TransparentMode = 
            (base.BackColor == Color.Transparent);
          this.InvalidateEx();
        }
    }
}

Now my controls allowed the transparent color, but the background was still getting painted black. Why? Because in my override of OnPaintBackground, I needed to call the base class when TransparentMode was set to true, to allow the parent Form to repaint the background:

protected override void OnPaintBackground
                    (PaintEventArgs pevent)
{
    if (TransparentMode)
    {
        base.OnPaintBackground(pevent);
        return;
    }

    PaintGradientBackground(pevent.Graphics);
}

There you have it, a few simple fixes. When I first started this toolkit, I didn't know how programmers set the transparent color. I made a mistake in having the TransparentMode property be public and totally ignoring BackColor. Now I've hidden TransparentMode from the Forms designer and allow programmers to do it the traditional way.

1 Comments

Cool controls. Very nice.

I couldn't find any contact info so i figured i would leave you something here.

In the trackbar control, you use the variable _currentTickValue, but the Value property changes the property _value which makes the property have no effect at all.

Second of all, when calculating the CurrentTickX and Y Corrdinate, you have to subtract the _minimum value. If the mimimum value is not 0, then the tick marks are redrawn correctly, but the minimum value is still 0.

Leave a comment