Reputation: 2519
I have a RichTextBox on VB.NET Winforms, and I want it to display (say) 12 lines of text in Liberation Mono 10pt font. I can resize it manually of course, but I want to programmatically resize it according to the font size and number of lines. The thing I'm struggling with is how to work out the height of a single line. I tried:
RichTextBox.Height = RichTextBox.Font.Height
and:
RichTextBox.Height = RichTextBox.Font.GetHeight
But neither seemed to give me the exact dimensions I wanted. Is there a way to measure the exact height of a line in a RTB?
Thanks @Arman, I did this in the end:
Public Function GetHeightOfFirstNumLines(ByVal RTB As RichTextBox, ByVal NumLines As Integer) As Integer
Dim Position1 = RTB.GetPositionFromCharIndex(RTB.GetFirstCharIndexFromLine(0))
Dim Position2 = RTB.GetPositionFromCharIndex(RTB.GetFirstCharIndexFromLine(NumLines))
Return Position2.Y - Position1.Y
End Function
Then in the Form.Load event, this code:
Dim RTBSize As New Size(TextRenderer.MeasureText("M", MemoryRtb.Font, MemoryRtb.Size, TextFormatFlags.WordBreak))
MemoryRtb.ClientSize = New Size(MemoryRtb.ClientSize.Width, (RTBSize.Height * 11) + 5)
Upvotes: 0
Views: 4084
Reputation: 78210
Lines can have different height, so you can do something like this:
Private Shared Function GetHeightOfFirstLines(ByVal Rtb As RichTextBox, ByVal NumLines As Integer) As Integer
Dim p1 = Rtb.GetPositionFromCharIndex(Rtb.GetFirstCharIndexFromLine(0))
Dim p2 = Rtb.GetPositionFromCharIndex(Rtb.GetFirstCharIndexFromLine(NumLines))
Return p2.Y - p1.Y
End Function
Then
RichTextBox1.ClientSize = New Size(RichTextBox1.ClientSize.Width, GetHeightOfFirstLines(RichTextBox1, 10))
This however requires that you already have 10 lines of text in the textbox. If you don't, you can get the height of the first line and assume the future ten lines will be of same height:
RichTextBox1.ClientSize = New Size(RichTextBox1.ClientSize.Width, GetHeightOfFirstLines(RichTextBox1, 1) * 10)
Upvotes: 1
Reputation: 1442
Use TextRenderer.MeasureText()
Dim rtbSize As New Size(TextRenderer.MeasureText(RichTextBox1.Text, RichTextBox1.Font, RichTextBox1.Size, TextFormatFlags.WordBreak))
RichTextBox1.Height = rtbSize.Height + 10
Upvotes: 2