Is there a way to color tabs of a tabpage in winforms?

后端 未结 3 706
醉酒成梦
醉酒成梦 2020-12-14 01:16

I am struggling to find a way to color the tab headers of a tabpage in WinForms. There are solutions to color the current indexed tab using the OnDrawItem event

3条回答
  •  没有蜡笔的小新
    2020-12-14 01:34

    An improved version of Ash's answer:

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

    This code uses the TextRenderer class to draw its text (as .NET does), fixes problems with font clipping/wrapping by not negatively inflating the bounds, and takes tab selection into account.

    Thanks to Ash for the original code.

提交回复
热议问题