如果我有一个名为BtnPlay
的按钮,如果用户按下它超过2次,我该如何显示消息框?
我尝试使用Select case
语句,但这似乎不起作用。
答案 0 :(得分:0)
问题是你在事件子中声明了你的计数器,因此每次用户按下按钮时,都会创建一个“新”计数器。在外面宣布它是一个golobal varible,你可以做到这一点。这样的事情:
Public Class Form1
Public PlayNum As Integer = 0
Private Sub BtnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPlay.Click
PlayNum = PlayNum + 1
If PlayNum > 2 Then
' Do the stuff you want when the user pressed more than two times.
Else
' Do something else
End If
End Sub
End Class
答案 1 :(得分:0)
每次输入PlayNum
时,BtnPlay_Click
都会重新初始化。因此要么扩大变量的范围并使其成为类的一个字段......
Public Class Form1
Private PlayNum As Integer
Private Sub BtnPlay_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles BtnPlay.Click
PlayNum += 1
If PlayNum > 2 Then
...
End If
End Sub
End Class
...或制作static。静态变量在对此方法的调用之间保留其值
Private Sub BtnPlay_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles BtnPlay.Click
Static PlayNum As Integer = 0
PlayNum += 1
If PlayNum > 2 Then
...
End If
End Sub
注意,静态变量在对象的生命周期(Form1类型)中只初始化一次。