c#textBox2文字居中
时间: 2023-11-22 12:47:37 浏览: 159
C# Winform中,TextBox控件默认不支持垂直居中文本的属性。但是可以通过计算文本高度并根据TextBox高度计算需要换行的行数的方式来实现类似于垂直居中的效果。具体实现方法如下:
1. 设置TextBox居中方式为水平居中:`textBox2.TextAlign = HorizontalAlignment.Center;`
2. 计算文本高度并根据TextBox高度计算需要换行的行数:
```csharp
Graphics graphics = Graphics.FromHwnd(ParentForm.Handle);
SizeF sizeF = graphics.MeasureString(textBox2.Text, textBox2.Font, textBox2.Width);
int lineHeight = (int)sizeF.Height / textBox2.Lines.Length;
int num = (textBox2.Height - (int)sizeF.Height) / (2 * lineHeight);
```
3. 将文本加入换行符:
```csharp
for (int i = 0; i < num; i++)
{
textBox2.Text = Environment.NewLine + textBox2.Text;
}
```
完整代码如下:
```csharp
textBox2.TextAlign = HorizontalAlignment.Center;
Graphics graphics = Graphics.FromHwnd(ParentForm.Handle);
SizeF sizeF = graphics.MeasureString(textBox2.Text, textBox2.Font, textBox2.Width);
int lineHeight = (int)sizeF.Height / textBox2.Lines.Length;
int num = (textBox2.Height - (int)sizeF.Height) / (2 * lineHeight);
for (int i = 0; i < num; i++)
{
textBox2.Text = Environment.NewLine + textBox2.Text;
}
```
阅读全文