有没有办法在winforms中为标签页的标签添加颜色?

Raj*_*Lal 27 .net c# winforms

我正在努力找到为WinForms中的标签页的标签标题着色的方法.有一些解决方案可以使用OnDrawItem事件为当前索引选项卡着色,但是可以一次为不同颜色的所有选项卡着色,以使用户对某种行为直观.

提前致谢,

Rajeev Ranjan Lall

g t*_*g t 47

Ash的答案的改进版本:

private void tabControl_DrawItem(object sender, DrawItemEventArgs e)
{
    TabPage page = tabControl.TabPages[e.Index];
    e.Graphics.FillRectangle(new SolidBrush(page.BackColor), e.Bounds);

    Rectangle paddedBounds = e.Bounds;
    int yOffset = (e.State == DrawItemState.Selected) ? -2 : 1;
    paddedBounds.Offset(1, yOffset);
    TextRenderer.DrawText(e.Graphics, page.Text, e.Font, paddedBounds, page.ForeColor);
}
Run Code Online (Sandbox Code Playgroud)

此代码使用TextRenderer类来绘制其文本(如.NET所示),修复字体剪切/包装的问题,不会对边界负面膨胀,并考虑选项卡选择.

感谢Ash的原始代码.

  • 仅当您将选项卡控件的 DrawMode 设置为 OwnerDrawFixed 时,这才有效 - 如果设置为 Normal,则 DrawItem 事件永远不会触发。 (4认同)
  • @Nitesh,此答案基于Ash的答案,并且该答案指示属性DrawMode设置为OwnerDrawFixed。 (2认同)

Ash*_*Ash 30

是的,不需要任何win32代码.您只需将选项卡控件DrawMode属性设置为'OwnerDrawFixed',然后处理选项卡控件的DrawItem事件.

以下代码显示了如何:

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    // This event is called once for each tab button in your tab control

    // First paint the background with a color based on the current tab

   // e.Index is the index of the tab in the TabPages collection.
    switch (e.Index )
    {
        case 0:
            e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
            break;
        case 1:
            e.Graphics.FillRectangle(new SolidBrush(Color.Blue), e.Bounds);
            break;
        default:
            break;
    }

    // Then draw the current tab button text 
    Rectangle paddedBounds=e.Bounds;
    paddedBounds.Inflate(-2,-2);  
    e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, this.Font, SystemBrushes.HighlightText, paddedBounds);

}
Run Code Online (Sandbox Code Playgroud)

将DrawMode设置为'OwnerDrawnFixed'意味着每个选项卡按钮必须具有相同的大小(即固定).

但是,如果要更改所有选项卡按钮的大小,可以将选项卡控件的SizeMode属性设置为"Fixed",然后更改ItemSize属性.

  • 效果很好,但是如何更改标签后面区域的颜色? (4认同)