Set TabPage Header Color

Theun Arbeider picture Theun Arbeider · Mar 17, 2011 · Viewed 67.9k times · Source

Greetings,

I have a tab control and I want to have 1 of the tabs have it's text color changed on a event. I've found answers like C# - TabPage Color event and C# Winform: How to set the Base Color of a TabControl (not the tabpage) but using these sets all colors instead of one.

So I was hoping there is a way to implement this with the tab I wish to change as a method instead of a event?

Something like:

public void SetTabPageHeaderColor(TabPage page, Color color) 
{
    //Text Here
}

Answer

Fun Mun Pieng picture Fun Mun Pieng · Mar 17, 2011

If you want to color the tabs, try the following code:

this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
this.tabControl1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabControl1_DrawItem);

private Dictionary<TabPage, Color> TabColors = new Dictionary<TabPage, Color>();
private void SetTabHeader(TabPage page, Color color)
{
    TabColors[page] = color;
    tabControl1.Invalidate();
}
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
    //e.DrawBackground();
    using (Brush br = new SolidBrush (TabColors[tabControl1.TabPages[e.Index]]))
    {
        e.Graphics.FillRectangle(br, e.Bounds);
        SizeF sz = e.Graphics.MeasureString(tabControl1.TabPages[e.Index].Text, e.Font);
        e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + (e.Bounds.Width - sz.Width) / 2, e.Bounds.Top + (e.Bounds.Height - sz.Height) / 2 + 1);

        Rectangle rect = e.Bounds;
        rect.Offset(0, 1);
        rect.Inflate(0, -1);
        e.Graphics.DrawRectangle(Pens.DarkGray, rect);
        e.DrawFocusRectangle();
    }
}