Re: Controlling SelText in TextBox...

From: Rick Rothstein (rickNOSPAMnews_at_NOSPAMcomcast.net)
Date: 07/21/04


Date: Wed, 21 Jul 2004 04:49:54 -0400


> I'm trying to impliment an auto-complete ability in a text box.
>
> The code I have is working fine unless the text is longer than the
textbox.
> This causes the view of the text to be shifted to the end of the line
where
> the cursor is.
>
> I'm trying to figure out how to select text, but keep the cursor where
the
> user left off typing (somewhere in the beginning of the line, not at
the
> end)
>
> IOW - the SelStart and SelLength assumen you want to at position 2
let's say
> for a length of 10. This puts the cursor at position 10. What I
> essentially need to do is SelStart at position 10 and select backwards
to
> position 2, so the whole text is selected but the cursor remains in
the
> beginning of the line.
>
> I hope this makes sense...

Let me first answer what I think you actually want, then I address the
more general condition you asked for. For the auto-complete you seem to
want to make sense, you would want what the user typed to be
unhighlighted and the remainder of the text you are providing for the
auto-complete to be completely highlighted to its end; but you want the
cursor to remain at the end of the text typed in by the user so far. See
if this code does that for you...

Dim TextTypedByUser As String
Dim AutoCompletedText As String

TextTypedByUser = "Sample"
AutoCompletedText = "Sample test text"

Text1.Text = AutoCompletedText
Text1.SelStart = Len(Text1.Text)
SendKeys "+{LEFT " & CStr(Len(Text1.Text) - _
                     Len(TextTypedByUser)) & "}"

You'll have to splice this into your existing code, but it does
highlight the remainder of the text while leaving the cursor at the
beginning of the highlighted text. Now, for the general question of
highlighting any substring of text while leaving the cursor at the
beginning of that selection. See if this code helps...

Dim StartPosition As Long
Dim LengthOfSelection As Integer

Text1.Text = "Highlight middle word"
StartPosition = InStr(Text1.Text, "middle") - 1
LengthOfSelection = Len("middle")

Text1.SelStart = StartPosition + LengthOfSelection
SendKeys "+{LEFT " & CStr(LengthOfSelection) & "}"

By the way, since this code is using SendKeys, it is important to make
sure that the TextBox has "focus" before executing the SendKeys line. I
assumed you were implementing highlight routine from the TextBox's
Change event. If not (for example, if you were using a CommandButton,
then you will have to issue a Text1.SetFocus command before you start
the above code.

Rick - MVP


Quantcast