exit loop when Escape key is pressed

Make a form level boolean set to false by default, then in the form's keyup event set the boolean to true if the that was pressed is the enter/return key then in your while loop add an AndAlso to the condition, testing the boolean of course
 
VB.NET:
Public Class Form1

    Private m_EscapeKeyPressed As Boolean = False

    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        m_EscapeKeyPressed = (e.KeyCode = Keys.Escape)
    End Sub
End Class
Now just use the boolean.

It might help to set that boolean to false right before the while loop starts if this loop runs more than once during the programs execution.
 
who to use m_EscapeKeypressed to the Loop?

For Example loop code is :

VB.NET:
dim x as integer = 0

do while x < 100000000
   .
   .
   .
   .
   x = x + 1
loop
 
who to use m_EscapeKeypressed to the Loop?

For Example loop code is :

VB.NET:
dim x as integer = 0

do while x < 100000000
   .
   .
   .
   .
   x = x + 1
loop
VB.NET:
dim x as integer = 0
m_EscapeKeyPressed = False
do while x < 100000000 AndAlso m_EscapeKeyPressed = False
   .
   .
   .
   .
   x += 1 'Same as x = x + 1, just less code
loop
 
not answer your Help , please check my code
 

Attachments

  • test.zip
    13.2 KB · Views: 21
Last edited by a moderator:
I edited your zip file and removed the compiled files (forum rules).

The problem with your example is that the loop's running on the UI thread (the thread that the form's on) so the form can't process it's KeyDown event until the loop finishes. Put 'Application.DoEvents' right after the 'x += 1' line in the loop, now try it.

For a small example like this, you might want to try using a smaller maximum value too:
VB.NET:
        With ProgressBar1
            .Minimum = 0
            .Value = 0
            .Maximum = 100000
            m_EscapeKeyPressed = False
            Dim x As Integer = .Minimum
            Do While x < .Maximum AndAlso m_EscapeKeyPressed = False
                ProgressBar1.Value = x
                Me.Text = x.ToString
                Application.DoEvents()
                x += 1
            Loop
        End With
 
Back
Top