Question Entering textbox and highlighting all contents - or not

J Trahair

Well-known member
Joined
May 14, 2008
Messages
175
Location
Spain
Programming Experience
10+
I have a normal form and normal textboxes. When the focus passes to a one-line textbox with text in it, I want to force the text to be selected and highlighted. When the focus passes to a multi-line textbox, I want to force the text to NOT be selected or highlighted, and the cursor to be at the end.

I have the code
HTML:
Private Sub TextBoxMultiLines_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBoxMultiLine1.Enter, TextBoxMultiLine2.Enter etc. etc.

        'Either:
        'CType(sender, TextBoxMultiLine1).SelectAll()
        'or:
        CType(sender, TextBox).SelectionLength = 0

End Sub
In this case (multi-line) the textbox is set for not selecting the text.
However, this only works after you have TABbed into the textbox, not when you press the Enter key (I have the code:
HTML:
    Private Sub TextBoxes_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress etc. etc.

        If e.KeyChar = Chr(Keys.Return) Then
            SendKeys.Send("{TAB}")
            e.Handled = True
        End If

    End Sub
which handles the Enter key press).

After the initial TAB, the code works fine when you use the Enter key. How can I overcome the 'use TAB key first' problem? Thank you in advance.
 
Have you tried the GotFocus-Event for this?

I'm using something pretty similar in my project, I've figured that this code works pretty neat:
VB.NET:
        If Not e.Handled Then
            If e.KeyCode = Keys.Return And Not e.Control Then
                Me.ProcessTabKey(Not e.Shift)
            End If
        End If
This code placed in a KeyDown-Event should work for you.

For setting the cursor at the end I'd use
VB.NET:
Me.TextBox.Select(Me.TextBox.Text.Length, 0)

Bobby
 
Back
Top