What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake a program with no forms that uses API timers and Sleep
DescriptionIf a program doesn't have any forms, it cannot use a Timer control. This example shows how to make a program without any forms that uses API timers in Visual Basic 6. It uses the Sleep API function to minimize CPU use while waiting for events.
KeywordsTimer, Timer control, time, speed, performance
CategoriesControls, API
The trick is to keep Sub Main running until the program is ready to exit. The program starts an API timer and then enters a loop where it sleeps for a while and then calls DoEvents. When the variable m_Running is False, the program ends the loop, kills the timer, and exits.

In some simple tests, a similar program without Sleep used more than 90 percent of the CPU but this version used only about 30 percent.

Private m_TimerID As Long
Private m_Running As Boolean

Private Sub Main()
    ' Start the timer.
    m_TimerID = SetTimer(0, 0, 3000, _
        AddressOf MyTimer)

    ' Run until the timer sets m_Running to False.
    m_Running = True
    Do While m_Running
        ' Pause a little while so we don't hog the CPU.
        Sleep 200

    ' Stop the timer.
    KillTimer 0, m_TimerID
End Sub

' See if the user wants to stop.
Public Sub MyTimer(hwnd As Long, msg As Long, idTimer As _
    Long, dwTime As Long)
Static i As Integer
Static messagebox_visible As Boolean

    ' Do nothing if another timer event is currently
    ' displaying the message box.
    If messagebox_visible Then Exit Sub

    messagebox_visible = True
    i = i + 1
    If MsgBox(i & ": Stop?", vbYesNo) = vbYes Then _
        m_Running = False
    messagebox_visible = False
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.