【问题标题】:Adding close button in tabpage tab caption in C# Windows Form在 C# Windows 窗体的标签页标签标题中添加关闭按钮
【发布时间】:2015-04-17 15:19:28
【问题描述】:

我正在尝试在 tabcontrol 的标签页面板上添加关闭按钮或“X”,并且通过阅读此 stackoverflow question 已成功完成此操作。

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

代码如下:

//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 的值,但它仍然无法正常工作。

【问题讨论】:

  • 这取决于 SizeMode。您可能希望在文本中添加几个空格以强制为 X 留出空间。或者您可以在将 X 添加到实际文本之前使用 measurestring 填充足够的空格,而无需单独绘制它。你将无法通过这种方式控制外观..

标签: c# winforms tabpage


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    确保将选项卡控件的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;
        }
    }
    

    上面示例代码的屏幕截图:

    【讨论】:

    • 嗨,是否有任何想法为所选标签设置颜色或任何图形?
    猜你喜欢
    • 2012-01-04
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2016-08-14
    相关资源
    最近更新 更多