Search code examples
c#painttabcontrolcustom-paintingcustom-draw

TabControl Custom Tab Bar Background Color


I have a TabControl where I needed to have custom tab colors. To do this, I set the DrawMode to OwnerDrawFixed, and overwrote the DrawItem event. However, when I change the DrawMode, it appears that the transparency for the Tab Bar is replaced with grey. I need to either make it transparent again, or change the color explicitly to the main page background color, but I can't figure out how to do this.

enter image description here

I can switch back and forth between OwnerDrawFixed and Normal, and see the transparency change in design mode, but even running under normal, I get the grey tab bar background.

My override code is below.

private void SettingsTabControl_DrawItem( object sender, DrawItemEventArgs e )
    {
        TabPage tab = SettingsTabControl.TabPages[e.Index];
        Rectangle header = SettingsTabControl.GetTabRect( e.Index );

        using (SolidBrush darkBrush = new SolidBrush( Color.FromArgb( 0, 68, 124 ) ))
        using (SolidBrush lightBrush = new SolidBrush( Color.FromArgb( 179, 191, 218 ) ))
        {
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            if (e.State == DrawItemState.Selected)
            {
                Font font = new Font( SettingsTabControl.Font.Name, 10, FontStyle.Bold );
                e.Graphics.FillRectangle( lightBrush, e.Bounds );
                e.Graphics.DrawString( tab.Text, font, darkBrush, header, sf );
            }
            else
            {
                e.Graphics.FillRectangle( darkBrush, e.Bounds );
                e.Graphics.DrawString( tab.Text, e.Font, lightBrush, header, sf );
            }
        }
    }

I'm also hoping to remove the grey border around the tab box but there doesn't seem to be a good way to do that outside of painting over the top of it. Is there a better way?


Solution

  • I added the following code to my SettingsTabControl_DrawItem method, which fixes this specific issue. I still have a border color issue, but I guess I can live with that.

    enter image description here

            //draw rectangle behind the tabs
            Rectangle lastTabRect = SettingsTabControl.GetTabRect( SettingsTabControl.TabPages.Count - 1 );
            Rectangle background = new Rectangle();
            background.Location = new Point( lastTabRect.Right, 0 );
    
            //pad the rectangle to cover the 1 pixel line between the top of the tabpage and the start of the tabs
            background.Size = new Size( SettingsTabControl.Right - background.Left, lastTabRect.Height + 1 );
    
            using (SolidBrush b = new SolidBrush( Colors.Get( Item.BorderBackground ) ))
            {
                e.Graphics.FillRectangle( b, background );
            }
    

    From here.