简体   繁体   English

vb.net 使用自动换行自动调整多行文本框高度

[英]vb.net Autosize Multiline Textbox height with wordwrap

I'm trying to make a fixed width textbox in a windows forms app in visual studio 2013 that will begin as a single line in height and expands as the user types and either the text wraps (wordwrap) or when the user pushes enter to create a new line.我正在尝试在 Visual Studio 2013 中的 Windows 窗体应用程序中制作一个固定宽度的文本框,该文本框将以单行高度开始,并随着用户键入和文本换行(自动换行)或用户按下 Enter 键而扩展一条新线。 Ideally i would like to set a max height at which point a vertical scroll bar would be added.理想情况下,我想设置一个最大高度,此时将添加垂直滚动条。 Also, the textbox should shrink when the user deletes content as well.此外,当用户删除内容时,文本框也应该缩小。

Would also much prefer to be able to use a rich text box however I would settle for a regular text box.也更希望能够使用富文本框,但我会满足于常规文本框。

Please tell me it doesn't require some crazy workaround to do what should be relatively easy.请告诉我它不需要一些疯狂的解决方法来做应该相对容易的事情。

Thanks in advance!!提前致谢!!

This worked for me:这对我有用:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
    Handles TextBox1.TextChanged
    TextBox1.Height = 
        TextRenderer.MeasureText(
            TextBox1.Text,
            TextBox1.Font,
            New Size(TextBox1.ClientSize.Width, 1000),
            TextFormatFlags.WordBreak
        ).Height
End Sub

If you want to use a rich textbox then try adding this to your form's class - remembering to rename all the bits that say"RichTextBox1" to the name of your richtextbox name如果您想使用富文本框,请尝试将其添加到表单的类中 - 记住将所有显示“RichTextBox1”的位重命名为您的富文本框名称

Private Sub richTextBox1_ContentsResized(sender As Object, e As contentsResizedEventArgs) Handles RichTextBox1.ContentsResized
    RichTextBox1.Height = e.NewRectangle.Height + 12
End Sub

The only downside of this is that whatever size you initially chose for your richtextbox, it will be ignored as the above event fires when the form loads唯一的缺点是,无论您最初为 Richtextbox 选择什么大小,它都会被忽略,因为在表单加载时会触发上述事件

我用了

txtBox.Height = txtBox.Font.Height * (txtBox.Lines.Count + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM