本文介绍了如何在Win表格中使组框文本对齐中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个分组框,其中有多个控件.
I am using a group box and there are several controls inside this.
我的要求是将组框标题设置为组框的中间位置,而不是"Left".
My requirement is to set the group box title to the middle of the group box instead of Left.
如何?
推荐答案
您可以像这样扩展组框类.
you can extend the group box class like this.
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",后者将在您的工具箱中生成后创建.
add the above class into your project and use "CustomGrpBox" instead of "GroupBox" which will be created after build in your tool box.
,您可以随时这样设置文本.
and you can set the text any time like this.
private void Form2_Load(object sender, EventArgs e)
{
customGrpBox1.Text = "Hello World";
}
在设计时视觉工作室中看起来像这样
it will look like this in design time visual studio
这篇关于如何在Win表格中使组框文本对齐中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!