首页 > 解决方案 > vb 应用程序中的按钮在第一次单击后在循环中每 x 次按下自身

问题描述

这是我的按钮,只需要知道我对 vb.net 很陌生

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

标签: vb.net

解决方案


最好在单击按钮时调用方法,而不是将代码放在那里 - 特别是如果您希望“每 x 次”执行一次单击。

Dim timer As New System.Threading.Timer(AddressOf doClickStuff)
Dim interval As Integer = 1000 ' 1000 ms = 1 second

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    doClickStuff()
End Sub

Private Sub doClickStuff()
    If Me.InvokeRequired Then
        Me.Invoke(New Action(AddressOf doClickStuff))
    Else
        ' do stuff here
        timer.Change(interval, -1)
    End If
End Sub

'' if you won't access UI elements in "do stuff here"
'' you can use this method which will run on a non-UI thread
'Private Sub doClickStuff()
'    ' do stuff here
'    timer.Change(interval, -1)
'End Sub

' stops the timer
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    timer.Change(-1, -1)
End Sub

推荐阅读