Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the content of textbox when it receives focus

I have found a similar question to mine in Making a WinForms TextBox behave like your browser's address bar

Now i am trying to modify or make it some more different by making it general. I want to apply same action to all the textboxes in form without write code for each one... how many i dun know. As soon as i add a textbox in my form it should behave with similar action of selecting.

So wondering how to do it?

like image 894
KoolKabin Avatar asked Dec 13 '22 21:12

KoolKabin


2 Answers

The following code inherits from TextBox and implements the code you mentioned in Making a WinForms TextBox behave like your browser's address bar.

Once you've added the MyTextBox class to your project you can do a global search for System.Windows.Forms.Text and replace with MyTextBox.

The advantage of using this class is you can't forget to wire all the events for every textbox. Also if you decide on another tweak for all textboxes you have one place to add the feature.

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
like image 131
Tim Murphy Avatar answered Jan 17 '23 15:01

Tim Murphy


Assuming you're going to use the accepted solution from the question you link to, all you'd need to do would be that whenever you create a new textbox, you use AddHandler to add the same 3 eventhandlers to each new textbox.

Then you need to change the event handlers to instead of referencing the textbox as this.textBox1 they'll reference it as CType(sender, TextBox) which means that they'll use the textbox that generated the event.

Edit: I'll add that line of code here as well since it's easier to read then

Private Sub TextBox_GotFocus (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus
like image 34
Hans Olsson Avatar answered Jan 17 '23 15:01

Hans Olsson