我正在编写一个程序,用户应该能够在 TextBox
中写入文本。我希望 TextBox
自行调整大小,以适应内容。
我尝试了以下方法:
private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
{
System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8);
System.Drawing.SizeF mySize = e.Graphics.MeasureString("This is a test", myFont);
this.textBoxTitle.Width = (int)Math.Round(mySize.Width, 0);
}
我收到一条错误消息,提示 Graphics
不适用于 TextChangedEventArgs
。还有其他方法可以调整 TextBox
的大小吗?
最佳答案
您应该尝试使用如下代码。它对我很有效。
private void textBox1_TextChanged(object sender, EventArgs e)
{
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
textBox1.Height = size.Height;
}
有关更多信息,请参阅 TextRenderer.MeasureText()
关于C# 调整文本框大小以适应内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8048455/