January 20, 2012

How to Change Color of Tab Control in C#

As there is no properties to change foreground and back ground color of tab control, it can be done by overriding the DrawItem event of the control.
Following are the steps involved to do the same.

1. Set the TabControl's DrawMode to OwnerDrawMode
2. Handle the DrawItem event to draw things.

Please see the following example;

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
//get tabpage
TabPage tabPages = tabControl1.TabPages[e.Index];
Graphics graphics = e.Graphics;
Brush textBrush = new SolidBrush(Color.Green); //fore color brush
Rectangle tabBounds = tabControl1.GetTabRect(e.Index);
if (e.State == DrawItemState.Selected)
           graphics.FillRectangle(Brushes.SkyBlue, e.Bounds); //fill background color
            textBrush = new System.Drawing.SolidBrush(e.ForeColor);
Font tabFont = new Font("Book Antiqua", 12, FontStyle.Italic | FontStyle.Bold, GraphicsUnit.Pixel);
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Near;
// draw text
graphics.DrawString(tabPages.Text, tabFont, textBrush, tabBounds, new StringFormat(strFormat));

No comments:

Post a Comment