vb.net 所有文本框上的自动全选和 gotfocus 上的 numericUpDown 控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14671713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:10:06  来源:igfitidea点击:

Automatic SelectAll on all textboxes and numericUpDown controls on gotfocus

vb.netwinformstextbox

提问by Wine Too

I have such code to make all text in textbox selected on got_focus:

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

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

Is here a way in VB.NET to get that all TextBoxes and NumericUpDown controls selects his text on _GotFocus or _Enter without to explicitly set such behavior for every single control and no matter how this control gets a focus (keyboard, mouse or programmatic)?

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

回答by spajce

Yes, there is and very simple.

是的,有而且非常简单。

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

回答by SNK

Public Class MyTextBox Inherits System.Windows.Forms.TextBox Private _focused As Boolean

公共类 MyTextBox 继承 System.Windows.Forms.TextBox Private _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

End Class

结束班