OK, here it comes...
[tt]
Option Explicit
Private Type Rect
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type CharRange
cpMin As Long ' First character of range (0 for start of doc)
cpMax As Long ' Last character of range (-1 for end of doc)
End Type
Private Type FormatRange
hdc As Long ' Actual DC to draw on
hdcTarget As Long ' Target DC for determining text formatting
rc As Rect ' Region of the DC to draw to (in twips)
rcPage As Rect ' Region of the entire DC (page size) (in twips)
chrg As CharRange ' Range of text to draw (see above declaration)
End Type
Private Const WM_USER As Long = &H400
Private Const EM_FORMATRANGE As Long = WM_USER + 57
Private Declare Function GetDC Lib "USER32" (ByVal hWnd As Long) As Long
Private Declare Function SetRect Lib "USER32" (lpRect As Rect, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal msg As Long, ByVal wp As Long, lp As Any) As Long
Private Sub Command1_Click()
RichTextBox1.Height = RTFHeight(RichTextBox1) ' + relevant border widths, if box has borders
End Sub
' Measure RTF height in a Richtextbox of a given width
' Change the width of the text box, and the result will change
' Note that returned value is the height of the text, and excludes
' any borders of the Richtextbox control
' Returns: height of text in twips
Public Function RTFHeight(RTF As RichTextBox) as long
Dim fr As FormatRange
Dim r As Long
Dim myrect As Rect
SetRect myrect, 0, 0, RTF.Width, 655360 ' Allows for a height of 43690 pixels
fr.hdc = GetDC(RTF.hWnd) ' Use the same DC for measuring and pretend rendering
fr.hdcTarget = GetDC(RTF.hWnd)
fr.rc = myrect ' Indicate the area on page to draw to
fr.rcPage = myrect ' Indicate entire size of page
fr.chrg.cpMin = 0 ' Indicate start of text through
fr.chrg.cpMax = -1 ' end of the text
SendMessage RTF.hWnd, EM_FORMATRANGE, False, fr
' Allow the RTF to free up memory
r = SendMessage(RTF.hWnd, EM_FORMATRANGE, False, ByVal CLng(0))
RTFHeight = fr.rc.Bottom
End Function