2

I'm using a While loop that loops a certain number of cycles (1-576) based on a value entered by a user. It's activated by the user clicking a "Start" button, But I would like it to be able to be canceled using, preferably, the "Escape" key.

However, when the loop is going I can't get the program to recognize any keypresses.

Private Sub OnGlobalKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles kh.KeyDown

        lblInput.Text = String.Format("'{0}' Code:{1}", e.KeyCode, CInt(e.KeyCode).ToString())


        If e.KeyCode = CType(27, Keys) Then
                    count = 0
                    loops = 0
        End If
    End Sub

My Loop

Private Sub RUNLOOP()
            While loops >= 1
                  ' my code that runs in the loop
                  loop = loop - 1
            End While
End Sub

While the loop is running my keypresses don't register, otherwise they register fine.

4

4 回答 4

5

Have you thought of using BackgroundWorker to perform the while loop code in a background thread, making sure your GUI keeps responsive (=resizing/redrawing the form and letting the user "reach" the way you implemented the cancelation of the running work) without needing Application.DoEvents inside the loop to "fake" this behavior?

If you are already on .NET Framework 4.0 you could try and use parallel programming instead of the BackgroundWorker.

于 2009-08-17T08:47:44.610 回答
2

有两种方法可以做到这一点。您可以为循环使用单独的线程或使用 Application.DoEvents()。线程方法通常会给你最好的结果。

线程:

您只需调用 StopLoop() 来告诉循环停止运行。您不想设置 loop = 0,因为这样您就必须使用 Interlocked 类来确保在线程之间正确设置循环。

Private Sub RunLoop()
  Dim loop As Action = AddressOf InternalRunLoop
  loop.BeginInvoke(null, null)
End Sub

Private bStopLoop As Boolean

Private Sub InternalRunLoop()
  While loops >= 1 And Not bStopLoop
    ' my code that runs in the loop
    loop = loop - 1
  End While
End Sub

Private Sub StopLoop()
  bStopLoop = True
End Sub

做事件:

调用 Application.DoEvents() 将导致处理窗口线程上的所有未决事件。如果循环的每次迭代都需要一些时间,那么应用程序在用户面前仍然会像无响应一样,这就是首选线程方法的原因。

Private SubRunLoop()
  While loops >= 1 And Not bStopLoop
    ' my code that runs in the loop
    loop = loop - 1
    Application.DoEvents()
  End While
End Sub
于 2009-08-17T09:02:37.607 回答
-1

Inside your loop place the following code:

Application.DoEvents()
于 2009-08-17T08:26:43.780 回答
-3
While counter <= 10
         ' skip remaining code in loop only if counter = 7
         If counter = 7 Then
            Exit While
         End If

         counter += 1
      End While
于 2009-08-17T08:35:26.773 回答