Date: 02-16-2022
Return to Index
created by gbSnippets
'Taking repeated action at fixed time intervals is a very common practice. The Windows
'SetTimer API can be used to create Windows timers which can trigger a response by
'an application in two ways - sending a %WM_Timer message to the dialog callback
'function or calling a specified procedure.
'A timer's interval cannot be changed on the fly. You have to destroy the timer and
'create a new one. Multiple timers can exist at one time.
'Primary Code:
'Here's sample code for each of the two ways to create a timer - depending on
'how you'd like the application to be notified at the end of each time interval. Note
'in both examples, %ID_Timer is an application defined timer integer. The 500 is
'the time interval in milliseconds.
SetTimer(hDlg, %ID_Timer, 500&, %NULL) 'sends %WM_Timer to dialog callback
SetTimer(hDlg, %ID_Timer, 500&, CodePTR(TimerProc)) 'call TimerProc each interval
'When the program is over, Windows will close the timer, but you can explicitly
'kill the timer with this:
KillTimer CB.Hndl, %ID_Timer
'Compilable Example: (Jose Includes)
'adapted from PowerBASIC Sample directory "digital.bas"
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "Win32API.inc"
%ID_Timer1 = 500 : %ID_Timer2 = 501
Global hDlg as DWord
Function PBMain () As Long
Dialog New Pixels, 0, "Timer",,, 150,100, %WS_OverlappedWindow To hDlg
Control Add Label, hDlg, 100, "", 10,10,100,20
Control Add Label, hDlg, 200, "", 10,40,100,20
Control Add Button, hDlg, 300, "Kill Timers", 10,70,100,20
Dialog Show Modal hDlg, Call DlgProc
End Function
CallBack Function DlgProc() As Long
Select Case CB.Msg
Case %WM_InitDialog
SetTimer(CB.Hndl, %ID_Timer1, 500, ByVal %NULL) 'uses callback messages
SetTimer(CB.Hndl, %ID_Timer2, 250, CodePTR(TimerSub)) 'calls TimerSub procedure each interval
' Dialog Post CB.Hndl, %WM_Timer, %ID_TIMER, 0 ' optional - forces an initial %WM_TIMER "event"
Case %WM_Timer
Static Count1 as Long
If CB.wParam = %ID_Timer1 Then
Count1 = Count1 + 1
Control Set Text hDlg, 100, Str$(Count1)
End If
Case %WM_Destroy
'would be a normal place to use KillTimer
Case %WM_Command
If CB.Ctl = 300 Then
KillTimer CB.Hndl, %ID_Timer1
KillTimer CB.Hndl, %ID_Timer2
End If
End Select
End Function
Sub TimerSub
Static Count2 as Long
Count2 = Count2 + 1
Control Set Text hDlg, 200, Str$(Count2)
End Sub
'gbs_00260
'Date: 03-10-2012
http://www.garybeene.com/sw/gbsnippets.htm