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
 
 
 
 
 
TitleMake a program that has no forms but that uses API timers
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.
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 DoEvents loop. When the variable m_Running is False, the program ends the loop, kills the timer, and exits.
 
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
        DoEvents
    Loop

    ' Stop the timer.
    KillTimer 0, m_TimerID
End Sub
 
When the timer fires, the program asks the user if it should continue. If it should not, the program sets m_Running to False.
 
' 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
 
NOTE: Stefan De Prins has these notes:

Allthough your technique works fine, you should take a look at the cpu usage when you do this. I once had to write a program that had to check wether Oracle was finshed indexing files before doing anyhting. I used the same technique (in Sub Main use doevents in a while loop and in my timer event check for the indexing every five minutes), the cpu usage went skyhigh). Therefore I had to use a form (which I know isn't what this example is about), and only start my actual code when in the timer event I could, that way the cpu usage stayed down untill I had to really start my actual code, and I do think this is essential on a server process, especially in my case where the actual code only took seconds, but I could have to wait maybe an hour before the Oracle indexing was finished, meaning I would be using the full server cpu time for that entire timespan. In short, be carefull when you use DoEvents. Many people still use it as a way to "kinda" make VB multi-threaded and believe me, VB isn't multithreaded !! ;-)
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated