Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleSize a RichTextBox to fit its contents
KeywordsRichTextBox, rich text, rtf, tab, drag, reposition
CategoriesControls
 
The RichTextBox control supports resize requests. When the control's contents or size change, the parent form receives the Windows message WM_NOTIFY. The message's lParam is a REQSIZE structure containing an nmhdr structure holding information about the request and a RECT structure containing the requested dimensions.

The program subclasses to watch for WM_NOTIFY messages.

 
Private Sub Form_Load()
    ... code deleted ...

    ' Subclass to watch for EN_REQUESTRESIZE messages.
    SetWindowProc Me.hWnd

    ... code deleted ...
End Sub
 
When it finds this message, it copies the first part of the lParam into an nmhdr structure and checks whether the request is EN_REQUESTRESIZE. If it is, the program copies the entire lParam into a REQSIZE structure and examines its RECT part to see how big the RichTextBox wants to be.
 
Private Type nmhdr
  hwndFrom As Long
  idfrom As Long
  code As Long
End Type

Private Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Private Type REQSIZE
    nmhdr As nmhdr
    RECT As RECT
End Type

' Look for the WM_NOTIFY message with an
' EN_REQUESTRESIZE message.
Public Function NewWindowProc(ByVal hWnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, ByVal lParam As Long) As _
    Long
    On Error Resume Next

    ' See if this is WM_NOTIFY
    If msg = WM_NOTIFY Then
        ' Copy lParam into the nmhdr structure,
        CopyMemory m_nmhdr, ByVal lParam, Len(m_nmhdr)

        ' See if this is an EN_REQUESTRESIZE.
        If m_nmhdr.code = EN_REQUESTRESIZE Then
            ' Copy lParam into the REQSIZE structure,
            CopyMemory m_ReqSize, ByVal lParam, _
                Len(m_ReqSize)

            ' Make the RichtextBox tall enough.
            SetWindowPos g_RchWnd, VBNullPtr, _
                0, 0, _
                g_RichWidth, m_ReqSize.RECT.Bottom - _
                    m_ReqSize.RECT.Top, _
                SWP_SHOWWINDOW Or SWP_NOMOVE
         End If
    End If ' If msg = WM_NOTIFY Then ...

    ' Call the original WindowProc.
    NewWindowProc = CallWindowProc(m_OldWindowProc, hWnd, _
        msg, wParam, lParam)
End Function
 
For more information, see the code and these Microsoft links:

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated