使用Paint事件重画GroupBox来修改边框颜色

来源:互联网 发布:淘宝找不到自己的店铺 编辑:程序博客网 时间:2024/06/07 04:03

.Net下进行WinForm开发,GroupBox是经常要用到的一个控件。但是GroupBox自身的边框是灰白色的,其样式很难令开发者满意。在不借用第三方控件的情况下,通过其的Paint事件对GroupBox进行重画,也可以很方便的修改其边框颜色/样式。

  简要说一下实现思路。首先用Clear方法清除GroupBox的显示,接着再用合适的样式把GroupBox画出来。把GroupBox拆分为4个圆角,一行标题文字和数段直线等元素,把这些元素摆放在合适的位置,拼凑出GroupBox的外框。定义4Rectangle(用于后面的画圆角),确定它们的大小和位置;然后在确切的位置上画4个弧段,按圆角在GroupBox上的位置确定其角度;接着在对应的位置画出GroupBox标题和几条直线,就大功告成了。只需简单修改代码中的设置颜色语句,便可以完成GroupBox边框颜色的更换了。

using System; 

usingSystem.Collections.Generic; 

usingSystem.ComponentModel; 

usingSystem.Data; 

usingSystem.Drawing; 

usingSystem.Drawing.Drawing2D; 

usingSystem.Text; 

usingSystem.Windows.Forms; 

 

namespaceWindowsApplication2 

     public partial class Form1 : Form 

     { 

         public Form1() 

         { 

             InitializeComponent(); 

         } 

         private void groupBox1_Paint(objectsender, PaintEventArgs e

         { 

            e.Graphics.Clear(groupBox1.BackColor); 

             Rectangle Rtg_LT = newRectangle(); 

             Rectangle Rtg_RT = newRectangle(); 

             Rectangle Rtg_LB = newRectangle(); 

             Rectangle Rtg_RB = newRectangle(); 

             Rtg_LT.X = 0; Rtg_LT.Y = 7; Rtg_LT.Width= 10; Rtg_LT.Height = 10; 

             Rtg_RT.X = e.ClipRectangle.Width -11; Rtg_RT.Y = 7; Rtg_RT.Width = 10; Rtg_RT.Height = 10; 

             Rtg_LB.X = 0; Rtg_LB.Y =e.ClipRectangle.Height - 11; Rtg_LB.Width = 10; Rtg_LB.Height = 10; 

            Rtg_RB.X = e.ClipRectangle.Width - 11;Rtg_RB.Y = e.ClipRectangle.Height - 11; Rtg_RB.Width = 10; Rtg_RB.Height =10; 

             Color color = Color.FromArgb(51,94, 168); 

            Pen Pen_AL = new Pen(color,1); 

             Pen_AL.Color = color; 

             Brush brush = newHatchBrush(HatchStyle.Divot, color); 

             e.Graphics.DrawString(groupBox1.Text, groupBox1.Font, brush, 6, 0); 

             e.Graphics.DrawArc(Pen_AL, Rtg_LT,180, 90); 

             e.Graphics.DrawArc(Pen_AL, Rtg_RT,270, 90); 

             e.Graphics.DrawArc(Pen_AL, Rtg_LB,90, 90); 

             e.Graphics.DrawArc(Pen_AL, Rtg_RB,0, 90); 

             e.Graphics.DrawLine(Pen_AL, 5, 7,6, 7); 

             e.Graphics.DrawLine(Pen_AL,e.Graphics.MeasureString(groupBox1.Text, groupBox1.Font).Width + 3, 7,e.ClipRectangle.Width - 7, 7); 

             e.Graphics.DrawLine(Pen_AL, 0, 13,0, e.ClipRectangle.Height - 7); 

             e.Graphics.DrawLine(Pen_AL, 6,e.ClipRectangle.Height - 1, e.ClipRectangle.Width - 7, e.ClipRectangle.Height -1); 

             e.Graphics.DrawLine(Pen_AL,e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 7, e.ClipRectangle.Width -1, 13); 

         } 

     } 

 }  运行效果图如下:


  代码稍显繁琐,但也很好的实现了修改GroupBox边框样式/颜色的效果。

0 0
原创粉丝点击