C# WinForm窗体控件GroupBox修改边框颜色控件
1.新建组件这里可以自定义一个GroupBox控件起名为GroupBoxEx
2.增加一个BoderColor属性
private Color _BorderColor = Color.Black; [Browsable(true),Description("边框颜色"),Category("自定义分组")]
public Color BorderColor
{
get { return _BorderColor; }
set
{
_BorderColor = value;
this.Invalidate();
}
}
3.控件代码继承GroupBox
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace ControlLibrary
{
public partial class GroupBoxEx : GroupBox
{
private Color _BorderColor = Color.Black; [Browsable(true),Description("边框颜色"),Category("自定义分组")]
public Color BorderColor
{
get { return _BorderColor; }
set
{
_BorderColor = value;
this.Invalidate();
}
} public GroupBoxEx()
{
InitializeComponent();
} public GroupBoxEx(IContainer container)
{
container.Add(this); InitializeComponent();
} /// <summary>
/// 重写Onpaint
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
var vSize = e.Graphics.MeasureString(this.Text,this.Font); e.Graphics.Clear(this.BackColor);
e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), , );
Pen vPen = new Pen(this._BorderColor);
e.Graphics.DrawLine(vPen, , vSize.Height / , , vSize.Height / );
e.Graphics.DrawLine(vPen, vSize.Width + , vSize.Height / , this.Width - , vSize.Height / );
e.Graphics.DrawLine(vPen, , vSize.Height / , , this.Height - );
e.Graphics.DrawLine(vPen, , this.Height - , this.Width - , this.Height - );
e.Graphics.DrawLine(vPen, this.Width - , vSize.Height / , this.Width - , this.Height - );
}
}
}
4.添加测试窗体并添加GroupBoxEx控件
编译运行