最近项目需要自定义tabControl控件颜色,而默认这个控件是不支持自定义标签颜色的,于是想办法实现了这个功能,效果如下图所示:
直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace CustomTabControl
{public partial class Form1 : Form{private TabControl tabControl;private TabPage tabPage1;private TabPage tabPage2;private TabPage tabPage3;public Form1(){// 初始化控件tabControl = new TabControl();tabPage1 = new TabPage("红");tabPage2 = new TabPage("绿");tabPage3 = new TabPage("蓝");// 添加 TabPage 到 TabControltabControl.TabPages.Add(tabPage1);tabControl.TabPages.Add(tabPage2);tabControl.TabPages.Add(tabPage3);// 设置 TabControl 的位置和大小tabControl.Location = new Point(25, 25);tabControl.Size = new Size(300, 200);// 设置 TabControl 为 OwnerDrawFixed 模式tabControl.DrawMode = TabDrawMode.OwnerDrawFixed;tabControl.DrawItem += new DrawItemEventHandler(tabControl_DrawItem);// 添加 TabControl 到 Formthis.Controls.Add(tabControl);// 设置 Form 的一些属性this.Text = "Custom TabControl Example";this.Size = new Size(350, 250);}// 处理 DrawItem 事件,自定义绘制 TabPage 标签private void tabControl_DrawItem(object sender, DrawItemEventArgs e){TabControl tc = (TabControl)sender;TabPage tp = tc.TabPages[e.Index];// 获取标签的边界Rectangle tabRect = tc.GetTabRect(e.Index);// 选择背景颜色Color backgroundColor;switch (tp.Text){case "红":backgroundColor = Color.Red;break;case "绿":backgroundColor = Color.Green;break;case "蓝":backgroundColor = Color.Blue;break;default:backgroundColor = SystemColors.Control; // 默认背景颜色break;}// 绘制背景using (SolidBrush backgroundBrush = new SolidBrush(backgroundColor)){e.Graphics.FillRectangle(backgroundBrush, tabRect);}// 使用系统默认的文字颜色绘制标签文本TextRenderer.DrawText(e.Graphics, tp.Text, tc.Font, tabRect, SystemColors.ControlText, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);}}
}