This works reasonably well...
I populated a RichTextBox
Dim sb As StringBuilder = New StringBuilder("")
For i = 1 To 20
sb.AppendLine("Lorem Ipsum etc")
Next
sb.Length -= Environment.NewLine.Length
RichTextBox1.Text = sb.ToString()
txtboxheight(RichTextBox1)
This is my interpretation of the txtboxheight routine
Private Sub Txtboxheight(rtb As RichTextBox)
Dim rtbSize As Size = TextRenderer.MeasureText(RichTextBox1.Text, RichTextBox1.Font)
RichTextBox1.Width = rtbSize.Width + (2 * RichTextBox1.Font.SizeInPoints)
RichTextBox1.Height = rtbSize.Height + RichTextBox1.Font.SizeInPoints
End Sub
MSDN reference -
TextRenderer Class (System.Windows.Forms)[
^]
Things to consider:
This assumes that all the lines are the same height - if you have added formatting then this might not be the case. You could possibly use the .Rtf property but if you do then the Width is not calculated properly.
For the addition of the "padding" at the bottom I've used the Font size (in points) as an arbitrary buffer - you might want to play around with that. Similarly for the width I used twice the font size which worked for all the fonts I tried.
If you don't adjust the width then be aware than having
WordWrap = True
will completely break the calculation