Denis Morgan

Denis Morgan

  • NA
  • 72
  • 20.7k

How to add a badge to a tabpage in a tabcontrol

Nov 18 2020 3:34 AM
I need to add a badge to a tab control at the top right corner. I have tried this and came up with this class
  1. public class BadgeUtil  
  2. {  
  3.     private static List<Control> controls = new List<Control>();  
  4.   
  5.     static public bool AddBadgeTo(Control ctl, string Text,int y,int x)  
  6.     {  
  7.         if (controls.Contains(ctl)) return false;  
  8.   
  9.         Badge badge = new Badge();  
  10.        // badge.AutoSize = true;  
  11.         badge.Size = new Size(20, 20);  
  12.         badge.Text = Text;  
  13.         badge.BackColor = Color.FromA#ff8040;  
  14.         controls.Add(ctl);  
  15.         ctl.Controls.Add(badge);  
  16.         SetPosition(badge, ctl,x,y);  
  17.   
  18.         return true;  
  19.     }  
  20.     static private void SetPosition(Badge badge, Control ctl,int x,int y)  
  21.     {  
  22.         badge.Location = new Point(x,  
  23.                                    y);  
  24.     }  
  25.     class Badge : Label  
  26.     {  
  27.         Color BackColor = Color.SkyBlue;  
  28.         Color ForeColor = Color.White;  
  29.         Font font = new Font("Sans Serif", 9f);  
  30.   
  31.         public Action<Control> ClickEvent;  
  32.   
  33.         public Badge() { }  
  34.   
  35.         protected override void OnPaint(PaintEventArgs e)  
  36.         {  
  37.             e.Graphics.FillEllipse(new SolidBrush(Color.FromA#ff0000),   
  38.                 this.ClientRectangle);  
  39.             e.Graphics.DrawString(Text, font, new SolidBrush(ForeColor), 3, 1);  
  40.         }  
  41.   
  42.         protected override void OnClick(EventArgs e)  
  43.         {  
  44.             ClickEvent(this);  
  45.         }  
  46.     }  
  47. }  
and used this way
  1. BadgeUtil.AddBadgeTo(tabPage3, "3",0,120);  
which is resulting to this un desired output. I would like my badge to be position on the blue circle of the tab control as shown in this image not where the badge is positioned.
 
 

Answers (5)