Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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.

like image 425
Rajeev Ranjan Lal Avatar asked Jan 21 '10 07:01

Rajeev Ranjan Lal


People also ask

How to change tabPage header color c#?

Answers. Hi, you need to draw it yourself. Change the DrawMode for the TabControl to OwnerDrawFixed and Fill the Bounds-Rectangle with the color you like and manually draw the headerText.


2 Answers

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.

like image 172
g t Avatar answered Oct 14 '22 17:10

g t


Yes, there is no need for any win32 code. You just need to set the tab controls DrawMode property to 'OwnerDrawFixed' and then handle the tab control's DrawItem event.

The following code shows how:

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

Setting the DrawMode to 'OwnerDrawnFixed' means each tab button has to be the same size (ie Fixed).

However if you want to change the size of all tab buttons, you can set the tab control's SizeMode property to 'Fixed' and then change the ItemSize property.

like image 43
Ash Avatar answered Oct 14 '22 18:10

Ash