VB Net Button做两件事

本文关键字:两件 Net Button VB | 更新日期: 2023-09-27 18:33:36

我希望我的按钮为其他按钮着色,并在再次单击时为其他按钮着色(第二次)....我正在尝试此代码。请帮帮我...

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

VB Net Button做两件事

e.Clicks不会做你认为它做的事情。 它不会跟踪表单生命周期内的总点击次数,而只是针对该事件。 由于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

另一种选择是将变量设置为静态。这将在方法调用之间将其值保留在内存中。

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
 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

这将基于布尔标志替换 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