我有代码突出显示当前焦点的文本框,以便为用户提供视觉提示。我的问题是,如果我有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
答案 0 :(得分:2)
如果要将此行为添加到所有TextBox控件,最好从TextBox类派生自己的类,并覆盖OnGotFocus
和OnLostFocus
方法以相应地设置属性。
以下是:
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中。然后你可以简单地拖动&像任何控件一样放在你的表格上。
干杯