When the focus moves to a Text Box that contains text,
Visual Basic 6’s default is to position the caret (editing cursor) at the start
of the text. In some applications, it might be more appropriate to have all of
the control’s text selected when it receives the focus. One advantage to this
is that it will delete the existing text if the user starts typing something
new. This tip shows you how to implement this behavior.
A Text Box has two properties that determine what text, if
any, is selected:
specifies the character position where the selection starts.
specifies the length of the selection, in characters.
You can select all text in a Text Box by setting SelStart to 0 and
to the length of the text. Here’s a short procedure that does this:
Sub SelectAllText(tb As TextBox)
tb.SelStart = 0
tb.SelLength = Len(tb.Text)
Then, for each Text Box that you want to behave this way,
call the procedure from the GotFocus event procedure, passing the name of the Text Box
as the argument:
Private Sub Text1_GotFocus()
This works when the Text Box gets the focus either by
tabbing or by a mouse click.
Peter Aitken has been programming with Visual Basic since Version
1.0. He has written numerous books and magazine articles on Visual Basic and
other computer and programming topics.