在gotfocus上的所有文本框和numericUpDown控件上自动选择SelectAll

时间:2013-02-03 10:55:23

标签: vb.net winforms textbox

我有这样的代码可以在got_focus中选择文本框中的所有文本:

Private Sub myText_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles myText.GotFocus
    myText.SelectAll()
End Sub

这是VB.NET中的一种方式,可以让所有TextBoxes和NumericUpDown控件在_GotFocus或_Enter上选择他的文本,而无需为每个控件显式设置此类行为,无论此控件如何获得焦点(键盘,鼠标或编程)?

2 个答案:

答案 0 :(得分:0)

是的,非常简单。

   Private Sub TextBox2_GotFocus(sender As Object, e As System.EventArgs) Handles TextBox2.GotFocus
        TextBox2.Select(0, TextBox2.Text.Length)
    End Sub

答案 1 :(得分:0)

Public Class MyTextBox     继承System.Windows.Forms.TextBox     私有_focused As Boolean

Protected Overrides Sub OnEnter(e As EventArgs)
    MyBase.OnEnter(e)
    If MouseButtons = MouseButtons.None Then
        SelectAll()
        _focused = True
    End If
End Sub

Protected Overrides Sub OnLeave(e As EventArgs)
    MyBase.OnLeave(e)
    _focused = False
End Sub

Protected Overrides Sub OnMouseUp(mevent As MouseEventArgs)
    MyBase.OnMouseUp(mevent)
    If Not _focused Then
        If SelectionLength = 0 Then
            SelectAll()
        End If
        _focused = True
    End If
End Sub

结束班