Resize richtextbox when contents change. VBE 2010

Need a RTB to resize when contents change. Tried this code I found on the internet but it works oddly because it seems to change the height but not the width (even though a debug shows the value for rtbCurrent.Width = CInt(sf.Width) is calculated to 199 [from 40]).

Something simple like this would be really useful, though.

        Dim g As Graphics = rtbCurrent.CreateGraphics
        Dim f As Font = rtbCurrent.Font
        Dim sf As SizeF = g.MeasureString(rtbCurrent.Text, f, rtbCurrent.Width)
        rtbCurrent.Height = CInt(sf.Height)
        rtbCurrent.Width = CInt(sf.Width)
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ess KayEntrapenuerCommented:
You can get if the control has scroll bars with this:

Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As IntPtr, ByVal nIndex As Integer) As Integer

And then call a function like this one after changing the text:

Private Sub ValidateTextBox(tb As RichTextBox)
    Dim Hdl As IntPtr = tb.Handle
    Dim Style, VBar As Integer

    tb.Width = iMinWidth
    Style = GetWindowLong(Hdl, GWL_STYLE)
    VBar = Style And WS_VSCROLL

    While VBar > 0 AndAlso tb.Width < iMaxWidth
        tb.Width += 24

        Style = GetWindowLong(Hdl, GWL_STYLE)
        VBar = Style And WS_VSCROLL
    End While
End Sub

Public Const WS_VSCROLL As Integer = &H200000
Public Const GWL_STYLE As Integer = (-16)

So essentiall, do the resizing in the validate method

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
author3000Author Commented:
Oh, the old Validate trick. :)

Thanks for the code. I've got it implemented and it has SOLVED MY PROBLEM.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.