C# WinForm窗体控件GroupBox修改边框颜色控件

C# WinForm窗体控件GroupBox修改边框颜色控件

1.新建组件这里可以自定义一个GroupBox控件起名为GroupBoxEx

 

2.增加一个BoderColor属性

 1         private Color _BorderColor = Color.Black;
 2 
 3         [Browsable(true),Description("边框颜色"),Category("自定义分组")]
 4         public Color BorderColor
 5         {
 6             get { return _BorderColor; }
 7             set 
 8             { 
 9                 _BorderColor = value;
10                 this.Invalidate();
11             }
12         }

3.控件代码继承GroupBox

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Diagnostics;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace ControlLibrary
11 {
12     public partial class GroupBoxEx : GroupBox
13     {
14         private Color _BorderColor = Color.Black;
15 
16         [Browsable(true),Description("边框颜色"),Category("自定义分组")]
17         public Color BorderColor
18         {
19             get { return _BorderColor; }
20             set 
21             { 
22                 _BorderColor = value;
23                 this.Invalidate();
24             }
25         }
26         
27         public GroupBoxEx()
28         {
29             InitializeComponent();
30         }
31 
32         public GroupBoxEx(IContainer container)
33         {
34             container.Add(this);
35 
36             InitializeComponent();
37         }
38 
39         /// <summary>
40         /// 重写Onpaint
41         /// </summary>
42         /// <param name="e"></param>
43         protected override void OnPaint(PaintEventArgs e)
44         {
45             //base.OnPaint(e);
46             var vSize = e.Graphics.MeasureString(this.Text,this.Font);
47 
48             e.Graphics.Clear(this.BackColor);
49             e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), 10, 1);
50             Pen vPen = new Pen(this._BorderColor);
51             e.Graphics.DrawLine(vPen, 1, vSize.Height / 2, 8, vSize.Height / 2);
52             e.Graphics.DrawLine(vPen, vSize.Width + 8, vSize.Height / 2, this.Width - 2, vSize.Height / 2);
53             e.Graphics.DrawLine(vPen, 1, vSize.Height / 2, 1, this.Height - 2);
54             e.Graphics.DrawLine(vPen, 1, this.Height - 2, this.Width - 2, this.Height - 2);
55             e.Graphics.DrawLine(vPen, this.Width - 2, vSize.Height / 2, this.Width - 2, this.Height - 2); 
56         }
57     }
58 }

4.添加测试窗体并添加GroupBoxEx控件

编译运行

源代码工程文件下载

posted @ 2018-05-09 16:48  JiYF  阅读(10345)  评论(0编辑  收藏  举报