C# – way to color tabs of a tabpage in winforms

cnetwinforms

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, but is it possible to color all the tabs with different colors to make them more intuitive for users for certain behavior?

Thanks in advance.

Best Answer

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.