using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MyNameSpace
{
public class M_GroupBox : GroupBox
{
private string _text = "";
/// <summary>
/// 构造函数
/// </summary>
public M_GroupBox() { base.Text = ""; }
[Browsable(true)]
[Category("Appearance")]
[DefaultValue("GroupBoxText")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public new string Text
{
get
{
return _text;
}
set
{
_text = value;
this.Invalidate();
}
}
/// <summary>
/// 重绘
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);//基类绘制控件
SolidBrush colorBrush = new SolidBrush(this.ForeColor);//创建前景色笔刷
var backColor = new SolidBrush(this.BackColor);//创建背景色笔刷
var size = TextRenderer.MeasureText(this.Text, this.Font);//测量文本大小
int left = (this.Width - size.Width) / 2;//从左边估算文本的位置;
//绘制一个填充矩形以便删除边框
e.Graphics.FillRectangle(backColor, new Rectangle(left, 0, size.Width, size.Height));
//绘制文本
e.Graphics.DrawString(this.Text, this.Font, colorBrush, new PointF(left, 0));
}
}
}
C#重绘GroupBox,使文本居中显示
于 2021-05-08 16:31:26 首次发布