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
 
 
 
 
TitleLet the user control a long process, displaying ellapsed time
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. in this example, the routine displays a count and uses DateDiff to display the ellapsed time since it started.

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
Dim start_time As Date
Dim diff As Long
Dim last_diff As Long
Dim txt As String

    i = 1
    start_time = Now
    last_diff = 0
    Do While Running
        i = i + 1
        CountLabel.Caption = Format$(i)

        diff = DateDiff("s", start_time, Now)
        If diff <> last_diff Then
            last_diff = diff
            txt = Format$(diff \ 60 \ 60, "00") & ":"
            diff = diff Mod 60
            txt = txt & Format$(diff \ 60, "00") & ":"
            diff = diff Mod 60
            txt = txt & Format$(diff, "00")
            lblEllapsedTime.Caption = txt
        End If

        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