TabControl 自定义标签栏背景色

TabControl Custom Tab Bar Background Color

我有一个需要自定义选项卡颜色的 TabControl。为此,我将 DrawMode 设置为 OwnerDrawFixed,并覆盖了 DrawItem 事件。但是,当我更改 DrawMode 时,选项卡栏的透明度似乎被替换为灰色。我需要让它再次透明,或者将颜色显式更改为主页背景颜色,但我不知道该怎么做。

我可以在 OwnerDrawFixed 和 Normal 之间来回切换,并在设计模式下看到透明度变化,但即使 运行 在 normal 下,我得到的是灰色标签栏背景。

我的覆盖代码如下。

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

我也希望删除选项卡框周围的灰色边框,但除了在其顶部绘画之外似乎没有什么好方法可以做到这一点。有没有更好的方法?

我将以下代码添加到我的 SettingsTabControl_DrawItem 方法中,它解决了这个特定问题。我仍然有边框颜色问题,但我想我可以接受。

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

来自 here.