我希望我的按钮为其他按钮着色,再次点击其他按钮时不同颜色(第二次)....我正在尝试此代码。请帮助我......
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
Dim visit As Integer = e.Clicks
visit = 0
If (visit = 1) Then
Button2.BackColor = Color.BlueViolet
Button3.BackColor = Color.Aqua
ElseIf (visit > 1) Then
Button2.BackColor = Color.Brown
Button3.BackColor = Color.Bisque
End If
visit += 1
End Sub
答案 0 :(得分:2)
e.Clicks
doesn't do what you think it does.它不跟踪表单生命周期内的总点击次数,仅针对该事件。由于visit
也在事件处理程序的范围内重新初始化,因此它总是会为每个事件重新启动。
跟踪该范围之外的总点击次数。像这样:
Dim visit as Integer = 0;
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
visit += 1
If (visit = 1) Then
Button2.BackColor = Color.BlueViolet
Button3.BackColor = Color.Aqua
ElseIf (visit > 1) Then
Button2.BackColor = Color.Brown
Button3.BackColor = Color.Bisque
End If
End Sub
只要该类保持在范围内,visit
将继续随每个事件递增。如果类本身也超出了范围(例如在Web表单上),那么您需要将visit
保持在更高的范围内,甚至可能超出应用程序状态本身。
你在这里尝试表达的逻辑也不完全清楚。首次点击后,ElseIf
条件将始终为真。您只是想在真值/假值之间切换而不是递增整数吗?像这样的东西?:
Dim visit as Boolean = False;
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
visit = Not visit
If (visit = True) Then
Button2.BackColor = Color.BlueViolet
Button3.BackColor = Color.Aqua
Else
Button2.BackColor = Color.Brown
Button3.BackColor = Color.Bisque
End If
End Sub
答案 1 :(得分:1)
另一个选项是将变量设置为静态。这将使它在方法调用之间保留在内存中的值。
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
Static visit As Integer = 0
visit += 1
If (visit = 1) Then
Button2.BackColor = Color.BlueViolet
Button3.BackColor = Color.Aqua
ElseIf (visit > 1) Then
Button2.BackColor = Color.Brown
Button3.BackColor = Color.Bisque
End If
End Sub
答案 2 :(得分:0)
Dim visit As Integer = 0;
Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick
If (visit = 0) Then
Button2.BackColor = Color.BlueViolet
Button3.BackColor = Color.Aqua
visit = 1
ElseIf (visit = 1) Then
Button2.BackColor = Color.Brown
Button3.BackColor = Color.Bisque
visit = 0
End If
End Sub
答案 3 :(得分:0)
这将基于布尔标志
交替button2的颜色Dim PrevClicked As Boolean = False
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If PrevClicked = False Then
Button2.BackColor = Color.Black
PrevClicked = True
Else
Button2.BackColor = Color.White
PrevClicked = False
End If
End Sub