多行文本框根据文本量自动调整高度

why*_*heq 7 c# winforms

我有一个文本框,可以返回各种字符串,长度从5个字符到1000个字符不等.它具有以下属性:

  • multiline = true
  • wordwrap = true

我需要设置文本框的哪些其他属性才能使以下内容成为可能?

  • 盒子的宽度应该是固定的
  • 框的高度可根据文本返回的数量自动调整,例如,如果文本运行到3行,则调整为3行高.

Com*_*ess 8

请尝试以下代码:

public partial class Form1 : Form
{
     private const int EM_GETLINECOUNT = 0xba;
     [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
     private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);


     public Form1()
     {
        InitializeComponent();
     }

     private void textBox1_TextChanged(object sender, EventArgs e)
     {
        var numberOfLines = SendMessage(textBox1.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
        this.textBox1.Height = (textBox1.Font.Height + 2) * numberOfLines;
     }
} 
Run Code Online (Sandbox Code Playgroud)

  • numberOflines = textbox1.lines.count(); (2认同)