Automatically adjust font size to fully fill Rich Textbox

In Visual Basic 6 we use the GetFirstVisible API to check if all the text in a Textbox is visible. We then decrease the font size until all text is visible.

We are looking to accomplish the same thing in Visual Basic 2008, in a Rich Textbox.

Attached is the Procedure we use to check if the font is too big to fit in the text box. If the procedure returns "True" then we make the font smaller and we call the Procedure again.

We would really prefer something like an "AutoFit" feature (like labels have), if this is possible.
Public Function FontTooBig(obj As Object) As Boolean
    Dim WindowHandle As Long
    WindowHandle = obj.hwnd
    obj.Selection.Range.StartPos = Len(obj.Text)
    LinesNotVisible = SendMessage(WindowHandle, EM_GETFIRSTVISIBLELINE, 0, 0)
    If LinesNotVisible <> 0 Then
        FontTooBig = True
        FontTooBig = False
    End If
End Function

Open in new window

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.

Wayne Taylor (webtubbs)Commented:
There is no method like "Autofit". The code you have is the best there is.


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
esmyhsAuthor Commented:
Thanks for the response. The problem that we are having with the attached code is that we get an error message on the following line:

WindowHandle = obj.hwnd

We get the following error message:

System.MissingMemberException was unhandled
  Message="Public member 'hwnd' on type 'RichTextBox' not found."
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.