单击按钮停止循环. [英] Stopping loop with button click.
问题描述
一个人一旦启动按钮单击相同的"Form1",将如何停止try循环?假设在此示例中p = 100.
How would a person stop a try loop once it has started a button click on the same "Form1'? Let's say in this example p = 100.
如果我想使用按钮将其停止,我已经搜索了Internet,但没有任何反应.
If I wanted to stop it using a button how would I, I have searched Internet and found nothing that is working.
* Dim p As Integer = CInt(textbox1.text)
对于计数器As Integer = p至1步骤-1
Label1.Text = counter.ToString
Application.DoEvents()
'另外,您最好使用结构化异常处理
试试
Threading.Thread.Sleep(1000)
' My.Computer.Audio.Play(My.Resources.SONAR,AudioPlayMode.WaitToComplete)
异常捕获
'发生错误时在这里处理
结束尝试
下一个
*Dim p As Integer = CInt(textbox1.text)
For counter As Integer = p To 1 Step -1
Label1.Text = counter.ToString
Application.DoEvents()
' Also you'd better use structured exception handling
Try
Threading.Thread.Sleep(1000)
' My.Computer.Audio.Play(My.Resources.SONAR, AudioPlayMode.WaitToComplete)
Catch ex As Exception
' handle here when an error occurs
End Try
Next
*由Spotty提供
*Courtesy of Spotty
推荐答案
使用计时器与消息调度程序协调循环:
Coordinate the loop with the message dispatcher using a timer:
私有 子 Button1_Click( ByVal 发件人 作为 对象 , ByVal e As EventArgs) 句柄 &Button1.点击
如果 Button1.Text = 开始"
其他
如果 整数 .TryParse(TextBox1.Text, Cnt) 然后
Button1.Text = 取消"
Timer1.Start()
结束 结束 结束 子
昏暗 整数
私有 Sub Timer1_Tick( ByVal sender 对象 , As EventArgs) 句柄 Timer1.Tick
Timer1.Stop()
Cnt -== nbsp; 1
Label1.Text = Cnt.ToString
如果 Cnt > 0 结束 Sub
结束 类
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If Button1.Text = "Cancel" Then
Timer1.Stop()
Button1.Text = "Start"
Else
If Integer.TryParse(TextBox1.Text, Cnt) Then
Button1.Text = "Cancel"
Timer1.Start()
End If
End If
End Sub
Dim Cnt As Integer
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
Cnt -= 1
Label1.Text = Cnt.ToString
If Cnt > 0 Then Timer1.Start()
End Sub
End Class
这篇关于单击按钮停止循环.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!