The difference in using timer between VB6 and C++
Boo Khan Ming
Posted on November 28, 2024
For those who did Visual Basic 6, you must be familiar with using timer control in your application. Just drag and drop the Timer from the Toolbox:
Then start writing code, just set the Interval of the timer in design time or run time.
For this example, the timer is set during run time:
Private Sub Form_Load()
Timer0.Interval= 3000
Timer0.Enabled=True
End Sub
Public Sub Timer0_Timer()
Beep
End Sub
And you will get this Form1 application running: (It is best if set Timer control to Visible=False
)
But how about using timer in other programming language? For example, in native Windows, C++ code can directly access the Win32 API to set and kill timer with callback.
Below are some example code taken from: https://learn.microsoft.com/en-us/windows/win32/winmsg/using-timers
Creating a Timer:
// Set two timers.
SetTimer(hwnd, // handle to main window
IDT_TIMER1, // timer identifier
10000, // 10-second interval
(TIMERPROC) NULL); // no timer callback
SetTimer(hwnd, // handle to main window
IDT_TIMER2, // timer identifier
300000, // five-minute interval
(TIMERPROC) NULL); // no timer callback
The callback to the GUI window is through WM_TIMER
message in the window procedure.
(We have to familiar ourselves with window class, window procedure, message loop, message queue while working with GUI window in Windows)
case WM_TIMER:
switch (wParam)
{
case IDT_TIMER1:
// process the 10-second timer
return 0;
case IDT_TIMER2:
// process the five-minute timer
return 0;
}
Or if initializing the timer with callback to your own TimerProc
procedure, the parameters to pass are a little different:
// Set the timer.
SetTimer(hwnd, // handle to main window
IDT_TIMER3, // timer identifier
5000, // 5-second interval
(TIMERPROC) MyTimerProc); // timer callback
Destroying a Timer
// Destroy the timers.
KillTimer(hwnd, IDT_TIMER1);
KillTimer(hwnd, IDT_TIMER2);
KillTimer(hwnd, IDT_TIMER3);
This is the screenshot of the GUI window with timer I created in FASM:
(It will beep every 3 seconds, but I am not posting the code on here anyway)
WM_TIMER
is a low-priority message among window messages like WM_PAINT
.
Make sure messages like WM_PAINT
does not block the message queue, or else WM_TIMER
message cannot be read.
Do you have other example of programming language to share, as to how to use timer in your software project?
Posted on November 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.