在C#Windows窗体的tabpage选项卡标题中添加关闭按钮

时间:2015-04-17 15:19:28

标签: c# winforms tabpage

我正在尝试添加关闭按钮或' X'在tabcontrol的tabpage面板上,我已经通过阅读stackoverflow question成功完成了这项工作。

问题是标签页标题和X标志合并在一起。我发现tabpage title面板没有根据标题文本调整大小。

以下是代码:

//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();

结果来了,我已经更改了e.bounds.right值,但它仍然无效。

2 个答案:

答案 0 :(得分:7)

要修复合并的tabPage.Text并另外绘制“X”,只需添加:

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

它会在每个tabPage的末尾添加一些额外的空间

答案 1 :(得分:5)

确保将选项卡控件的DrawMode属性设置为OwnerDrawFixed。此属性决定系统或开发人员是否绘制字幕。

以下是使用TabSizeMode = Fixed设置标签大小的代码示例:

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;
    }
}

上面示例代码的屏幕截图: Tab Size in Action