我有以下代码(VB.Net)正在做我想要的(即在代码的特定间隔/位置暂停和单击Messagebox按钮时恢复)....... 唯一的问题是我使用了一个消息框;有没有办法使用按钮代替做同样的工作;没有计时器,没有消息框?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Index As Integer
For KKK = 1 To 50
Index = KKK / 5
If Index = KKK / 5 Then
MessageBox.Show("Paused at: " & KKK & " : Click OK to Resume")
End If
Next
End Sub
提前感谢您的评论和帮助。
答案 0 :(得分:0)
需要2个按钮和一个标签。试试这个:
Dim Pause As Boolean
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Index As Integer
Pause = False
Button2.Text = "Ok"
Button2.Enabled = False
For KKK = 1 To 50
System.Threading.Thread.Sleep(250) 'Just for testing purposes, do not use this instruction.
Index = KKK / 5
If Index = KKK / 5 Then
Label1.Text = "Paused at: " & KKK & " : Click OK to Resume"
Pause = True
Button2.Enabled = True
Button2.Focus()
While Pause
Application.DoEvents()
End While
Label1.Text = ""
Button2.Enabled = False
End If
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Pause = False
End Sub
答案 1 :(得分:0)
如果您升级到VS2013社区(免费),那么您可以像这样使用Async / Await组合:
Public Class Form1
Private MRE As New Threading.ManualResetEvent(False)
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Button2.Enabled = False
For KKK = 1 To 50
If KKK Mod 5 = 0 Then
Label1.Text = KKK
MRE.Reset()
Button2.Enabled = True
Await WaitForButton()
End If
Next
Button1.Enabled = True
End Sub
Private Function WaitForButton() As Task
Return Task.Run(Sub()
MRE.WaitOne()
End Sub)
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Button2.Enabled = False
MRE.Set()
End Sub
End Class
答案 2 :(得分:-1)
您可以通过将循环放入单独的线程,暂停休眠并通过单击按钮中断它来完成此操作。在此示例中,button1启动循环,button2在thread.sleep
处中断它。
Dim newThread As New Thread(AddressOf loopSub)
Delegate Sub textAddCallback(ByVal s As string)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newThread.Start()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
newThread.Interrupt()
End Sub
Sub loopSub()
Dim Index As Integer
Dim textDelegate As New textAddCallback(AddressOf textAdd)
Try
For KKK As Integer = 1 To 50
Index = KKK / 5
If Index = KKK / 5 Then
Thread.Sleep(36000) ' sleep the max amount of milliseconds
End If
Next
Catch ex As ThreadInterruptedException
Me.Invoke(textDelegate, "string to add")
End Try
End Sub
Sub textAdd(ByVal s As String)
rtext1.text &= s
End Sub