Friday, February 24, 2012

.NET transparent label control

Spent a good deal of time this morning trying to make the background of a label control transparent (to go over a dynamically expanding Panel of a different color).  You would think simply setting the background property to Transparent would do the trick, but not so.  Here is the code:



 class mtClearLabel : Label  
   {  
     public override string Text  
     {  
       get  
       {  
         return base.Text;  
       }  
       set  
       {  
         base.Text = value;  
         if (this.Parent != null)  
           this.Parent.Invalidate(this.Bounds, true);  
       }  
     }  
     public mtClearLabel()  
     {  
       this.SetStyle(ControlStyles.Opaque, true);  
       this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);        
     }  
     protected override CreateParams CreateParams {  
       get {  
         CreateParams parms = base.CreateParams;  
         parms.ExStyle |= 0x20; // Turn on WS_EX_TRANSPARENT  
         return parms;  
       }  
     }  
     protected override void OnPaintBackground(PaintEventArgs pevent)  
     {  
       //do nothing  
     }  
   }  

1 comment: