我的系统上有几个按钮,单击按钮时我尝试更改颜色焦点。到目前为止,我的编码只能在点击时更改按钮颜色,但我希望我的系统能够在点击其他按钮时将按钮颜色重置为正常颜色。
我试图在网站上找到解决方案,但我真的不明白,因为他们的样本对我来说太复杂了。
这是我改变按钮颜色焦点的简单编码。
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
请帮助我。谢谢。
答案 0 :(得分:1)
在声明部分中创建2个颜色变量,一个用于background属性,另一个用于forecolor属性。您必须在窗体的事件Load中将Button1的Background颜色和Foreground颜色属性分配给这些变量。当您单击Button1时,它会随您执行的代码而更改,当您单击其他按钮时,它会通过使用颜色变量来恢复Button1颜色。我希望这个解释可以帮到你。以下是进一步说明的完整代码。
Public Class Form1 Dim bgColor,foColor As Color
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Button1.BackColor = Color.Yellow
Button1.ForeColor = Color.Blue
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles Button2.Click
Button1.BackColor = bgColor
Button1.ForeColor = foColor
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
bgColor = Button1.BackColor
foColor = Button1.ForeColor
End Sub
结束班
答案 1 :(得分:1)
由于用户可以在没有点击的情况下专注于按钮,因此最好处理按钮的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