我在Making a WinForms TextBox behave like your browser's address bar中找到了一个类似于我的问题的解决方案。现在我想要修改或者改进它,使其更加通用。我希望将同样的操作应用于表单中的所有文本框,而不需要为每个文本框编写代码...我不知道有多少个。只要我在表单中添加一个文本框,它就应该具有类似选择的相似动作。
所以我想知道怎么做?
所以我想知道怎么做?
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
Private Sub TextBox_GotFocus (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus
Private Sub TextBox_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus
。 - Hans OlssonPublic 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