C#调整大小的文本框,以适应内容 [英] C# Resize textbox to fit content

查看:986
本文介绍了C#调整大小的文本框,以适应内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,用户应该能够在文本框中写入文本。我想文本框来调整自己,所以它适合内容。
我已经试过如下:

I'm writing a program where the user should be able to write text in a textbox. I'd like the textbox to resize itself, so it fit the content. I've tried the following:

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

我得到一个错误,说图形不适合TextChangedEventArgs工作。有另一种方法,我可以调整文本框?

I get an error saying that Graphics doesn't work for TextChangedEventArgs. Is there another way I can resize the textbox?

推荐答案

您应该尝试code类似下面。它为我工作很好。

You should try a code something like below. It has worked for me well.

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

For more information refer to TextRenderer.MeasureText()

这篇关于C#调整大小的文本框,以适应内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆