How to auto scroll a richtextbox in Visual Basic .Net

J

JonnyT

I searched high and low for an answer on how to auto scroll a
richtextbox and now I finally have it. Since it took me a while to
get a good efficient way of doing it that didn't require focus to the
control or the scrolltocaret method I decided that it would be worth
posting to anyone who might have similar concerns. For the record
this works well in an environment where you cannot have focus going to
the richtextbox....such as a chat program or something similar. If
you are able to set focus to the form then use this method

richtextbox.selectionstart = richtextbox.textlength
richtextbox.scrolltocaret()

I think that should do it...can't remember offhand...something like
that though.

Now if you cannot set the focus to the richtextbox then this will work
well for you.
When you want to display text in the richtext box use the
..appendtext("sometext") method. That's what it's there for.
Then you will need the sendmessage API...

Public Declare Function SendMessage Lib "user32.dll" Alias _
"SendMessageA" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal
wParam As Integer, ByVal lParam As Integer) As Integer

and you will also need a couple constants...

Public Const EM_GETLINECOUNT = &HBA
Public Const EM_LINESCROLL = &HB6

Now the way I do it works great for me....

I figure out how many line are in the richtextbox before adding my new
text to it....I do that with the following...

Dim intLines As Integer = SendMessage(richtextbox.Handle,
EM_GETLINECOUNT, 0, 0)

then add your text

richtextbox.appendtext("your text here")

you will know how many lines to scroll down with by running the
EM_GETLINECOUNT after you added your new text like so

Private intLinesToAdd as integer = (SendMessage(richtextbox.Handle,
EM_GETLINECOUNT, 0, 0) - intTotalLines)

Now that you know how many lines have been added...you know how many
lines your scroll bar needs to scroll down.
We use this line to scroll the scroll bar down...

SendMessage(richtextbox.Handle, EM_LINESCROLL, 0, intLinesToAdd)

I've changed it a little from my original code to make it easier for
you to use...I hope it still works how it's suppose to. If not I
think you get the jist of it.


JonnyT
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top