tags:

views:

325

answers:

2

I am struggling to find way to color the tab headers of a tabpage in WinForms. There are solutions to color the current indexed tab using OnDrawItem event but can it be possible to color all the tabs with different colors at a time to make them intuitive for user for a certain behavior.

Thanks in advance,

Rajeev Ranjan Lall

+1  A: 

Using the current tab control, if it is possible you'd need to hook a lot of win-32 events (there may be a pre-wrapped implementation out there). Another alternative would be a 3rd-party tabbed control replacement; I'm sure plenty of vendors will sell you one.

IMO, you might find it less pain to look at WPF; it is a big change, but has more control over things like this. You can host WPF inside winforms if needed (if you can't justify a full make-over, which is a pretty common reality).

Marc Gravell
+7  A: 

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.

Ash