Select the contents of the text field when receiving focus

I found a similar question for mine in Creating WinForms TextBox behaves like the address bar of your browser

Now I'm trying to change or make it different by making it general. I want to apply the same action to all text fields in a form without code for each of them ... as far as I know. As soon as I add a text box to my form, it should behave with a similar selection action.

So wondering how to do this?

+3
source share
3 answers

TextBox , WinForms TextBox, .

, MyTextBox , System.Windows.Forms.Text MyTextBox.

, . , , .

Imports System
Imports System.Windows.Forms

Public Class MyTextBox
    Inherits TextBox

    Private alreadyFocused As Boolean

    Protected Overrides Sub OnLeave(ByVal e As EventArgs)
        MyBase.OnLeave(e)

        Me.alreadyFocused = False

    End Sub

    Protected Overrides Sub OnGotFocus(ByVal e As EventArgs)
        MyBase.OnGotFocus(e)

        ' Select all text only if the mouse isn't down.
        ' This makes tabbing to the textbox give focus.
        If MouseButtons = MouseButtons.None Then

            Me.SelectAll()
            Me.alreadyFocused = True

        End If

    End Sub

    Protected Overrides Sub OnMouseUp(ByVal mevent As MouseEventArgs)
        MyBase.OnMouseUp(mevent)

        ' Web browsers like Google Chrome select the text on mouse up.
        ' They only do it if the textbox isn't already focused,
        ' and if the user hasn't selected all text.
        If Not Me.alreadyFocused AndAlso Me.SelectionLength = 0 Then

            Me.alreadyFocused = True
            Me.SelectAll()

        End If

    End Sub

End Class
+7

, , , , , , , , AddHandler 3 .

this.textBox1, CType(sender, TextBox), , , .

: , ,

Private Sub TextBox_GotFocus (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus
+3

:

Public Class TextBoxX
    Inherits System.Windows.Forms.TextBox

    Private Sub TextBoxX_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
        SelectAll()
    End Sub
end class

You can see the full project of our TextBox (on steroids) on GitHub https://github.com/logico-dev/TextBoxX

+1
source

Source: https://habr.com/ru/post/1753651/


All Articles