我的系统上没有几个按钮,并且在单击按钮时尝试更改颜色焦点。到目前为止,我的编码只能在单击时更改按钮的颜色,但是我希望我的系统在单击其他按钮时也能够将按钮的颜色重置为正常颜色。
我试图在网站上找到解决方案,但我真的不明白怎么做,因为他们的样本对我来说太复杂了。
这是更改按钮颜色焦点的简单代码。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Button1.BackColor = Color.Gainsboro
Me.Button1.ForeColor = Color.Black
End Sub
请帮助我。谢谢你。
由于用户无需单击即可专注于按钮,因此最好处理按钮的事件GotFocus
和LostFocus
事件,并在其中放置逻辑。
在下面的代码,我分配一个处理这些事件在形式所有按钮和存储的原始ForeColor
和BackColor
在数据结构Tag
属性。然后在GotFocus
中将ForeColor
和设置BackColor
为所需的focusedForeColor
和focusedBackColor
。同样在中,LostFocus
我恢复了以前存储在中的原始前色和背景色Tag
。
将此代码粘贴到您的表单代码中就足够了,它适用于所有按钮:
'Change these to your desired color
Private focusedForeColor As Color = Color.Black
Private focusedBackColor As Color = Color.Gainsboro
Private Function GetAllControls(control As Control) As IEnumerable(Of Control)
Dim controls = control.Controls.Cast(Of Control)()
Return controls.SelectMany(Function(ctrl) GetAllControls(ctrl)).Concat(controls)
End Function
Public Sub New()
InitializeComponent()
Me.GetAllControls(Me).OfType(Of Button)().ToList() _
.ForEach(Sub(b)
b.Tag = Tuple.Create(b.ForeColor, b.BackColor)
AddHandler b.GotFocus, AddressOf b_GotFocus
AddHandler b.LostFocus, AddressOf b_LostFocus
End Sub)
End Sub
Private Sub b_LostFocus(sender As Object, e As EventArgs)
Dim b = DirectCast(sender, Button)
Dim colors = DirectCast(b.Tag, Tuple(Of Color, Color))
b.ForeColor = colors.Item1
b.BackColor = colors.Item2
End Sub
Private Sub b_GotFocus(sender As Object, e As EventArgs)
Dim b = DirectCast(sender, Button)
b.ForeColor = focusedForeColor
b.BackColor = focusedBackColor
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句