Microsoft KB Archive/161240

= How To Select All Text in a Field When It Gets the Focus =

Article ID: 161240

Article Last Modified on 7/13/2004

-

APPLIES TO


 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 6.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q161240



SUMMARY
Automatic highlighting is useful in data entry boxes where you want to give the user the option to overwrite the existing contents quickly by pressing any character key.

This article demonstrates how to select (highlight) all text in a text box automatically whenever the text box gets the focus. This example also applies to the ComboBox and Grid control and any other controls that implement the Text, SelStart, and SelLength properties.



Step-by-Step Example
 Start Visual Basic, or, if it is already running, click New Project from the File menu. Place two Text Boxes on the Form1 form with the default settings.  Copy and paste the following code to the Form1 Code Window: Private Sub Text1_GotFocus Call SelectMe(Me.ActiveControl) End Sub

Private Sub Text2_GotFocus Call SelectMe(Me.ActiveControl) End Sub

Private Sub SelectMe(This As TextBox) This.SelStart = 0 This.SelLength = Len(This.Text) End Sub

 Press the F5 key to run the project, or click Run Project from the Tools menu.

As you move to each text box, the text is highlighted. If you begin typing, the text will be replaced with your new entry. To deselect the text after giving focus to the text box, you can single-click the text or press any of the TextBox navigation keys (Home, End, Arrow-Keys).

