Pls Hlp: How can I make my custom labels have transparent backgrounds

S

ShakeDoctor

Hi, I have a custom label control which is clickable.
However, the background of the label is white, and you can't set it to
transparent in the property window because it says it is not supported.

Here is the code, what do i need to add to make the BackColor transparent?


public class CustomLabel : Control
{
public ContentAlignment TextAlignment = ContentAlignment.TopLeft;

public CustomLabel()
{
}

protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground (e);
}

protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;

SolidBrush brush = new SolidBrush(this.ForeColor);
SizeF s;

s = graphics.MeasureString(this.Text, this.Font);

switch (this.TextAlignment)
{
case ContentAlignment.TopCenter:
graphics.DrawString(this.Text, this.Font, brush, (this.Width - s.Width)
/ 2,(this.Height - s.Height) / 2);
break;

case ContentAlignment.TopLeft:
graphics.DrawString(this.Text, this.Font, brush, 2, (this.Height -
s.Height)/ 2);
break;

case ContentAlignment.TopRight:
graphics.DrawString(this.Text, this.Font, brush, this.Width - s.Width -
2,(this.Height - s.Height) / 2);
break;
}

brush.Dispose();

base.OnPaint (e);
}

public override string Text
{
get {return base.Text;}
set
{
base.Text = value;
//Force to repaint
this.Invalidate();
}
}
 
S

ShakeDoctor

yes of course I have, and the only information I could find was adding this
to the controls constructor:

SetStyle(ControlStyles.SupportsTransparentBackColor, true);

BackColor =
System.Drawing.Color.FromArgb(0,System.Drawing.Color.Transparent);

However, the ControlStyles enumeration isn't available as far as I know.

So the only way of achieving it is to not paint the background at all? or
paint the background as the colour you want (i.e. not real transparency)
 
S

ShakeDoctor

hmmm, that link isn't too handy.

And if I do a search for "transparent label", they all seem to be people
trying to draw text over a picturebox.

Normal labels seem to have a transparent background already, its just my
clickable label doesn't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top