C# WinForms TabControl头部默认背景色无法移除问题求助
解决C# WinForms TabControl头部顶部默认背景色问题
方法1:重写WndProc完全自定义绘制头部
WinForms TabControl的顶部默认背景是系统主题绘制的区域,默认自定义绘制仅覆盖标签本身,我们可以通过拦截WM_PAINT消息,手动绘制整个头部区域来覆盖默认背景。
示例代码:
public class CustomTabControl : TabControl { protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0xF) // 拦截WM_PAINT消息 { using (Graphics g = Graphics.FromHwnd(Handle)) { // 绘制头部整体背景(替换为你需要的颜色) var headerRect = new Rectangle(0, 0, Width, ItemSize.Height + 2); g.FillRectangle(new SolidBrush(Color.FromArgb(45, 45, 48)), headerRect); // 逐个绘制标签的背景与文本 for (int i = 0; i < TabCount; i++) { var tabRect = GetTabRect(i); var tabBgBrush = SelectedIndex == i ? new SolidBrush(Color.FromArgb(60, 60, 63)) : new SolidBrush(Color.FromArgb(45, 45, 48)); g.FillRectangle(tabBgBrush, tabRect); TextRenderer.DrawText( g, TabPages[i].Text, Font, tabRect, SelectedIndex == i ? Color.White : Color.Gray, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter ); } // 移除默认边框 ControlPaint.DrawBorder(g, ClientRectangle, Color.Transparent, ButtonBorderStyle.None); } } } public CustomTabControl() { // 开启自定义绘制相关样式,避免闪烁和默认绘制干扰 SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true); Appearance = TabAppearance.Normal; SizeMode = TabSizeMode.Fixed; ItemSize = new Size(120, 30); } }
方法2:通过Region裁剪隐藏顶部默认背景
如果不想完全重绘,可通过裁剪TabControl的区域,隐藏顶部默认背景,同时调整标签位置使其正常显示:
示例代码:
public class CustomTabControl : TabControl { protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); // 裁剪掉顶部默认背景区域 Region = new Region(new Rectangle(0, ItemSize.Height, Width, Height - ItemSize.Height)); // 调整标签位置到顶部 for (int i = 0; i < TabCount; i++) { var tabRect = GetTabRect(i); tabRect.Y = 0; SetTabRect(i, tabRect); } } public CustomTabControl() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true); Appearance = TabAppearance.Buttons; SizeMode = TabSizeMode.Fixed; ItemSize = new Size(120, 30); } protected override void OnPaint(PaintEventArgs e) { // 绘制每个标签的背景与文本 foreach (TabPage page in TabPages) { int index = TabPages.IndexOf(page); var tabRect = GetTabRect(index); e.Graphics.FillRectangle( SelectedIndex == index ? new SolidBrush(Color.FromArgb(60, 60, 63)) : new SolidBrush(Color.FromArgb(45, 45, 48)), tabRect ); TextRenderer.DrawText( e.Graphics, page.Text, Font, tabRect, SelectedIndex == index ? Color.White : Color.Gray, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter ); } // 绘制TabPage区域边框(可选) var clientRect = ClientRectangle; clientRect.Y = ItemSize.Height; clientRect.Height -= ItemSize.Height; e.Graphics.DrawRectangle(Pens.DarkGray, clientRect); } }
关键注意事项
- 必须开启
ControlStyles.UserPaint、AllPaintingInWmPaint和DoubleBuffer,避免绘制闪烁和默认系统绘制的干扰 - 自定义绘制时要覆盖头部所有区域,不要依赖
Appearance属性的默认样式 - 两种方法都需要将TabControl替换为自定义的
CustomTabControl类使用
内容的提问来源于stack exchange,提问作者Kalababu
相关产品推荐
相关产品推荐

