0

我有代码突出显示当前文本框,以便为用户提供视觉提示。我的问题是,如果我有 10 个带有文本框的表单,并且我想为它们都提供相同的代码。我必须复制它还是可以使用全局方法?如果是这样,一个例子将非常有帮助。谢谢。

代码如下。

Private Sub FocusChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim txt As TextBox = sender
    If txt.Focused Then
        txt.Tag = txt.BackColor
        txt.BackColor = Color.AliceBlue
    Else
        txt.BackColor = txt.Tag
    End If
End Sub
Private Sub CreateAccount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each ctrl As TextBox In Me.Controls.OfType(Of TextBox)()
        AddHandler ctrl.GotFocus, AddressOf FocusChanged
        AddHandler ctrl.LostFocus, AddressOf FocusChanged
        ctrl.Tag = ctrl.BackColor
    Next
End Sub
4

1 回答 1

2

如果要将此行为添加到所有 TextBox 控件,最好从 TextBox 类派生自己的类,并重写OnGotFocusOnLostFocus方法以相应地设置属性。

就是这样:

Public Class MyTextBox
    Inherits TextBox

    Protected Overrides Sub OnGotFocus(e As System.EventArgs)
        MyBase.OnGotFocus(e)
        Me.Tag = Me.BackColor
        Me.BackColor = Color.Aqua
    End Sub

    Protected Overrides Sub OnLostFocus(e As System.EventArgs)
        MyBase.OnLostFocus(e)
        Me.BackColor = Me.Tag
    End Sub
End Class

编辑:忘了提到在将该类添加到您的项目后,重新构建解决方案,如果它编译没有错误,那么您的新 TextBox 类将显示在 VS ToolBox 中。然后,您可以像任何控件一样简单地拖放到您的表单上。

干杯

于 2012-10-23T01:27:51.197 回答