| {\rtf1\ansi\ansicpg1252\deff0\deflang1044{\fonttbl{\f0\fnil\fcharset0 MS Sans Serif;}} \viewkind4\uc1\pard\f0\fs17 If you have a project that doesn't have a form, but you need a timer you could add a form just for that purpose. But that would be waste of resources. This code snippet makes use of the AddressOf keyword introduced in VB 5.0 to create a callback function. Don't click the stop button while this program is running if KillTimer hasn't been called yet as VB will properly crash. \par \par Create a new project remove the form and add a new module. Place this code into the module \par \par 'Declarations section: \par Private Declare Function SetTimer Lib "user32" _ \par (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, _ \par ByVal lpTimerFunc As Long) As Long \par Private Declare Function KillTimer Lib "user32" _ \par (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long \par Dim TimerID As Long \par \par \par Sub Main is the entry point to this application. The SetTimer function will cause TimerFunc to be called every three seconds. This program loops until the Timer is killed. If the loop wasn't there TimerFunc would continue to run once the program had ended (and properly cause VB to crash). The important thing to remember is to kill the timer before the application finishes. \par \par Sub Main() \par TimerID = SetTimer(0, 0, 3000, AddressOf TimerFunc) \par ' Loop until the timer is killed by the user \par Do \par DoEvents \par Loop While TimerID <> -1 \par End Sub \par \par \par This is the sub receives the timer events. \par \par 'hwnd : handle of window for timer messages \par 'uMsg : WM_TIMER message \par 'idEvent: timer identifier \par 'dwTime : current system time \par Public Sub TimerFunc(ByVal hwnd As Long, ByVal uMsg As Long, _ \par ByVal idEvent As Long, ByVal dwTime As Long) \par MsgBox "Time=" & dwTime & ". Click ok to Kill the Timer" \par If KillTimer(0, TimerID) <> 0 Then ' Killed the Timer \par TimerID = -1 \par End If \par End Sub \par } |
Creating a Timer without a Form |
India web developer web development India | India web development company India ecommerce web developer