我在Making a WinForms TextBox behave like your browser's address bar
中找到了类似的问题现在我试图通过使它变得通用来修改或使它更加不同。我想对表单中的所有文本框应用相同的操作,而不是每个文本框都有代码...我知道多少个。只要我在表单中添加一个文本框,它就应该采用类似的选择操作。
所以想知道怎么做?
答案 0 :(得分:7)
以下代码继承自TextBox并实现您在Making a WinForms TextBox behave like your browser's address bar中提到的代码。
将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
答案 1 :(得分:3)
假设您要使用链接到的问题中的已接受解决方案,您需要做的就是每当您创建新文本框时,使用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
答案 2 :(得分:2)
我们使用此自定义文本框控件:
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
你可以在GitHub https://github.com/logico-dev/TextBoxX上看到我们TextBox的完整项目(关于类固醇)