gpt4 book ai didi

c# - 如何在winforms中使分组框文本居中?

转载 作者:太空狗 更新时间:2023-10-29 22:36:44 28 4
gpt4 key购买 nike

我正在使用一个组框,里面有几个控件。

我的要求是将组框标题设置到组框的中间而不是左侧。

如何?

最佳答案

您可以像这样扩展组框类。

 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));

}
}

将上面的类添加到您的项目中,并使用“CustomGrpBox”而不是“GroupBox”,后者将在您的工具箱中构建后创建。

并且您可以像这样随时设置文本。

private void Form2_Load(object sender, EventArgs e)
{
customGrpBox1.Text = "Hello World";
}

it will look like this in design time visual studio

在设计时 Visual Studio 中看起来像这样

关于c# - 如何在winforms中使分组框文本居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827366/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com