How do I change the color of each tab?
I have a form that has four tabs. I would like each tab to be a different color. The only thing I have been able to find on the internet is to change the color of the selected tab, and the rest of the tabs will remain the same. I haven't found anything to give each tab its own color. The code I have is there.
Private Sub TabControl1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem
Dim g As Graphics = e.Graphics
Dim tp As TabPage = TabControl1.TabPages(e.Index)
Dim br As Brush
Dim sf As New StringFormat
Dim r As New RectangleF(e.Bounds.X, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 2)
sf.Alignment = StringAlignment.Center
Dim strTitle As String = tp.Text
If TabControl1.SelectedIndex = e.Index Then
'this is the background color of the tabpage header
br = New SolidBrush(Color.LightSteelBlue) ' chnge to your choice
g.FillRectangle(br, e.Bounds)
'this is the foreground color of the text in the tab header
br = New SolidBrush(Color.Black) ' change to your choice
g.DrawString(strTitle, TabControl1.Font, br, r, sf)
Else
'these are the colors for the unselected tab pages
br = New SolidBrush(Color.Blue) ' Change this to your preference
g.FillRectangle(br, e.Bounds)
br = New SolidBrush(Color.Black)
g.DrawString(strTitle, TabControl1.Font, br, r, sf)
End If
End Sub
source to share
There are two things you need to do:
First you need to change DrawMode TabControl and set it to OwnerDrawFixed
And the second is to handle the DrawControl DrawItem event
Here's an example:
Private Sub TabControl1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles TabControl1.DrawItem
Select Case e.Index
Case 0
e.Graphics.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
Case 1
e.Graphics.FillRectangle(New SolidBrush(Color.Blue), e.Bounds)
Case 2
e.Graphics.FillRectangle(New SolidBrush(Color.Magenta), e.Bounds)
End Select
Dim paddedBounds As Rectangle = e.Bounds
paddedBounds.Inflate(-2, -2)
e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text, Me.Font, SystemBrushes.HighlightText, paddedBounds)
End Sub
And this is how it looks (I only change the colors of the pills on the first three pages of the tab, the rest can be easily done by adding new cases to select a case)
source to share
Is TabControl1 a Tab control that you add to the form through the constructor? Why not just set the TabBackColor property for each tab when you create it?
If not (you need to do this with code), just use a loop to cycle through each tab in the TabControl1 collection of tabs (TabControl1.TabPages) and set the TabBackColor property for each one.
source to share