你可以像这样扩展分组框类。
public class CustomGrpBox : GroupBox
{
private string _Text = "";
public CustomGrpBox()
{
//set the base text to empty
//base class will draw empty string
//in such way we see only text what we draw
base.Text = "";
}
//create a new property a
[Browsable(true)]
[Category("Appearance")]
[DefaultValue("GroupBoxText")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public new string Text
{
get
{
return _Text;
}
set
{
_Text = value;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
//first let the base class to draw the control
base.OnPaint(e);
//create a brush with fore color
SolidBrush colorBrush = new SolidBrush(this.ForeColor);
//create a brush with back color
var backColor = new SolidBrush(this.BackColor);
//measure the text size
var size = TextRenderer.MeasureText(this.Text, this.Font);
// evaluate the postiong of text from left;
int left = (this.Width - size.Width) / 2;
//draw a fill rectangle in order to remove the border
e.Graphics.FillRectangle(backColor, new Rectangle(left, 0, size.Width, size.Height));
//draw the text Now
e.Graphics.DrawString(this.Text, this.Font, colorBrush, new PointF(left, 0));
}
}
Run Code Online (Sandbox Code Playgroud)
将上述类添加到您的项目中,并使用“CustomGrpBox”而不是“GroupBox”,后者将在您的工具箱中构建后创建。
你可以像这样随时设置文本。
private void Form2_Load(object sender, EventArgs e)
{
customGrpBox1.Text = "Hello World";
}
Run Code Online (Sandbox Code Playgroud)
它在设计时视觉工作室中看起来像这样
小智 5
不幸的是,您可以使用 RightToLeft 属性将标题设置在右侧,但没有将其设置在中间的属性。
您可以做的是在 GroupBox 中设置一个空文本,创建一个带有标题的 Label 并将该标签放在 GroupBox 上方(具有相同的父级)。
您可以通过调用以下过程在表单初始化时动态执行此操作:
private void CenterGroupBoxTitle(GroupBox groupbox)
{
Label label = new Label() ;
label.Text = groupbox.Text ;
groupbox.Text = "" ;
label.Left = groupbox.Left+(groupbox.Width-label.Width)/2 ;
label.Top = groupbox.Top + 2 ; // 2 is an example : adjust the constant
label.Parent = groupbox.Parent ;
label.BringToFront() ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13175 次 |
| 最近记录: |