Adding close button in tabpage tab caption in C# Windows Form

Vivek Singh picture Vivek Singh · Apr 17, 2015 · Viewed 13.7k times · Source

I am trying to add close button or 'X' on tabpage panel in tabcontrol and I have successfully done this by reading this stackoverflow question.

The problem is the tabbed page title and X sign is merged together. I discovered that the tabpage title panel is not resizing according to title text.

Here is the code:

//This code will render a "x" mark at the end of the Tab caption. 
e.Graphics.DrawString("X", e.Font, Brushes.Black, e.Bounds.Right + 15, e.Bounds.Top + 4);
e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left+5, e.Bounds.Top + 4);

e.DrawFocusRectangle();

The result which comes is here I have changed e.bounds.right value but still it's not working.

Answer

SoCo picture SoCo · Apr 2, 2016

To fix merged tabPage.Text with additionally drawed "X" just add:

tabControl.Padding = new System.Drawing.Point(21, 3);

It will add some extra space to the end of every tabPage