微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – 在获得焦点时选择文本框的内容

我在 Making a WinForms TextBox behave like your browser’s address bar找到了类似的问题

现在我试图通过使它变得通用来修改或使其更加不同.我想对表单中的所有文本框应用相同的操作,而不是每个文本框都有代码…我知道多少个.只要我在表单中添加一个文本框,它就应该采用类似的选择操作.

所以想知道怎么做?

解决方法

以下代码继承自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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐