前期工作:
加载资源文件,双击“Resources.resx"
类型选择Images
【添加资源】——【添加现有文件】
选择需要添加的图片文件,保存即可。
在下面的资源文件夹中即可看到添加的图片列表
**方法一:**重绘标签及背景
新建窗体,命名为"OtherForm.cs"
窗体布局如图:
将【tabControl】控件的【DrawMode】属性修改为”OwnerDrawFixed“
设计界面变为
tabControl控件的事件属性页,添加【DrawItem】事件
编辑【DrawItem】事件
private void tabControl2_DrawItem(object sender, DrawItemEventArgs e){//加载背景图片Image imgButton = Properties.Resources.p4; Image imgBJ = Properties.Resources.p5;//绘制主控件的背景Rectangle Rect = new Rectangle(0, 0, this.tabControl2.Width, this.tabControl2.Height);e.Graphics.DrawImage(imgBJ, Rect);//新建一个StringFormat对象,用于对标签文字的布局设置StringFormat stringFormat = new StringFormat();stringFormat.LineAlignment = StringAlignment.Center; // 设置文字垂直方向居中stringFormat.Alignment = StringAlignment.Center; // 设置文字水平方向居中 SolidBrush bruFont = new SolidBrush(Color.FromArgb(255, 255, 255));// 标签字体颜色Font font = new System.Drawing.Font("楷体", 10F, FontStyle.Bold);//设置标签字体样式//绘制标签样式 for (int i = 0; i < tabControl2.TabPages.Count; i++){//获取标签头的工作区域Rectangle rec = tabControl2.GetTabRect(i);Rectangle newRect = new Rectangle(rec.Left - 7, rec.Top, rec.Width - 7, rec.Height);//绘制标签头背景颜色e.Graphics.DrawImage(imgButton, newRect);//绘制标签头的文字e.Graphics.DrawString(tabControl2.TabPages[i].Text, font, bruFont, newRect, stringFormat);} }
运行结果
**方法二:**重写TabControl控件
重写TabControl控件可以改变其背景为透明或绘制背景图,绘制标签风格等各种,但是在X64编辑环境下,重写的控件无法直接拖拽到界面进行设计,需要在修改”main.Designercs"中修改代码。
新建窗体,命名为"main.cs"
窗体布局如图:
在main.cs文件中加入以下代码
public class TabControlEx : TabControl{private Color _BackColor; //背景颜色public TabControlEx(){this.SetStyle(ControlStyles.UserPaint, true);//用户自己绘制this.SetStyle(ControlStyles.ResizeRedraw, true);this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); //this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//让控件支持透明色this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);this.UpdateStyles();}public override Color BackColor{//重写backcolor属性 get{return this._BackColor;}set{this._BackColor = value;}}protected override void OnPaint(PaintEventArgs e){this.DrawTitle(e.Graphics);base.OnPaint(e);}protected virtual void DrawTitle(Graphics g){Image imgButton = Properties.Resources.p;StringFormat sf = new StringFormat();sf.Alignment = StringAlignment.Center;sf.LineAlignment = StringAlignment.Center;Font font = new System.Drawing.Font("微软雅黑", 10F, FontStyle.Bold);//设置标签字体样式using (SolidBrush sb = new SolidBrush(Color.FromArgb(127, 0, 0, 0))){for (int i = 0; i < this.TabPages.Count; i++){Rectangle rect = this.GetTabRect(i);Rectangle newRect = new Rectangle(rect.Left + 7, rect.Top, rect.Width - 7, rect.Height);g.DrawImage(imgButton, newRect);g.DrawString(this.TabPages[i].Text, font, Brushes.White, rect, sf);}}}}
注:上面有些代码是不需要的,是其他功能的。
在main.Designer.cs中将原来的this.tabControl = new System.Windows.Forms.TabControl();改为this.tabControl = new TabControlEx();
程序运行结果: