Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleAllow the user to start and stop a long process
Keywordslong process, start, stop
CategoriesSoftware Engineering
 
Use a form-level Boolean variable Running to tell the procedure when to stop. The RunLongProcess subroutine is the long process in this example. It periodically calls DoEvents to let the program process button clicks and then checks Running to see if it should still be running.

The CmdStart_Click event handler checks Running to see if the long process is currently running. If the process is running, the user is trying to stop the process so the program sets Running to False to tell RunLongProcess to stop.

If the process is not running, the user is trying to start it. The program sets Running = True and calls RunLongProcess.

 
Private Running As Boolean

Private Sub RunLongProcess()
Dim i As Long

    i = 1
    Do While Running
        i = i + 1
        CountLabel.Caption = Format$(i)
        
        DoEvents ' Very important!
    Loop
End Sub

Private Sub CmdStart_Click()
    If Running Then
        ' The process is running. Stop it.
        Running = False
        CmdStart.Caption = "Stopping"
        CmdStart.Enabled = False
    Else
        ' The process is not running. Start it.
        ' Prepare the button.
        CmdStart.Caption = "Stop"
        DoEvents
        
        ' Perform the long process. It will stop
        ' when Running is False. That happens when
        ' RunLongProcess calls DoEvents and the
        ' user has clicked Stop. At that point
        ' this routine is called again and the code
        ' above runs, changing the button's caption
        ' and disabling it.
        Running = True
        RunLongProcess
        
        CmdStart.Caption = "Start"
        CmdStart.Enabled = True
    End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated