Adding a close button on a tabbed tab in C # Windows Form

I'm trying to add a close button or "X" on a tab bar to a tabcontrol, and I've successfully done so by reading this question about stack_surface .

The problem is the title of the tabbed page and the X is concatenated. I found that the tab title bar does not resize to fit the 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 that appears here, I changed the value e.bounds.right

, but still it doesn't work.

+3


source to share


2 answers


Make sure the DrawMode property of the tab control is OwnerDrawFixed . This property decides whether the system or the developer will draw the decals.

Here is some sample code that uses TabSizeMode = Fixed to set the size of a bookmark:



public partial class Form1 : Form
{
    const int LEADING_SPACE = 12;
    const int CLOSE_SPACE = 15;
    const int CLOSE_AREA = 15;

    public Form1()
    {
        InitializeComponent();
    }

    private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
    {
        //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 - CLOSE_AREA, e.Bounds.Top + 4);
        e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + LEADING_SPACE, e.Bounds.Top + 4);
        e.DrawFocusRectangle();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // get the inital length
        int tabLength = tabControl1.ItemSize.Width;

        // measure the text in each tab and make adjustment to the size
        for (int i = 0; i < this.tabControl1.TabPages.Count; i++)
        {
            TabPage currentPage = tabControl1.TabPages[i];

            int currentTabLength = TextRenderer.MeasureText(currentPage.Text, tabControl1.Font).Width;
            // adjust the length for what text is written
            currentTabLength += LEADING_SPACE + CLOSE_SPACE + CLOSE_AREA;

            if (currentTabLength > tabLength)
            {
                tabLength = currentTabLength;
            }
        }

        // create the new size
        Size newTabSize = new Size(tabLength, tabControl1.ItemSize.Height);
        tabControl1.ItemSize = newTabSize;
    }
}

      

Screenshot of the example code above: Tab Size in Action

+5


source


To fix the merged tabPage.Text with an extra highlighted "X" just add:

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

      



It will add extra space to the end of each tab

+7


source







All Articles