1

I've created a transparent label control and the transparency works great. However, I find when I update the control's Text field, the original Text doesn't clear before it paints the new text. So if I change the control's Text field several times, it soon becomes unreadable.

Any clues? Thanks!

public partial class TransLabel : Label
{
    public TransLabel()
    {
        InitializeComponent();

        this.SetStyle(ControlStyles.Opaque, true);
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
        this.Font = new Font("Franklin Gothic Book", 12f, FontStyle.Regular);
        this.ForeColor = Color.White;
        this.BackColor = Color.Transparent;
    }

    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = value;
            this.Invalidate(); // seems to have no effect
            this.Refresh(); // seems to have no effect
        }
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        //do nothing
    }

    protected override void OnMove(EventArgs e)
    {
        RecreateHandle();
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle = 0x00000020; //WS_EX_TRANSPARENT
            return cp;
        }
    }
}
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
simon.d
  • 2,471
  • 3
  • 33
  • 51
  • I think you can call the `.Refresh()` method on the form? I don't know for sure... – psyklopz Jan 25 '12 at 18:27
  • If memory serves, you need to erase the contents of the label in the `OnPaintBackground` event. I know I've run into this before when I've created custom controls, although mine weren't transparent, so I'm not 100% sure. – CodingGorilla Jan 25 '12 at 18:31

1 Answers1

1

Try changing your Text property to this:

public override string Text {
  get {
    return base.Text;
  }
  set {
    base.Text = value;
    if (this.Parent != null)
      this.Parent.Invalidate(this.Bounds, false);        
  }
}

Since WinForms doesn't have true support for transparency, I think you have to invalidate the parent container.

Also, when inheriting a control, you usually don't have an InitializeComponent() method.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • The above control only works fine if does not overlap another control which repaints itself periodically, like a progressbar. The label will disappear and start to flash-in on redraw of the progressbar. – Legends Jan 23 '18 at 01:33