The following example uses the SetTimer function to create two timers. The first timer is set for every 10 seconds, the second for every 5 minutes.
// Set two timers.
SetTimer(hwnd, // handle of main window
IDT_TIMER1, // timer identifier
10000, // 10-second interval
(TIMERPROC) NULL); // no timer callback
SetTimer(hwnd, // handle of main window
IDT_TIMER2, // timer identifier
300000, // 5-minute interval
(TIMERPROC) NULL); // no timer callback
To process the WM_TIMER messages generated by these timers, add a WM_TIMER case statement to the window procedure for the hwnd parameter.
case WM_TIMER:
switch (wParam)
{
case IDT_TIMER1:
// Process the 10-second timer.
return 0;
case IDT_TIMER2:
// Process the 5-minute timer.
return 0;
}
An application can also create a timer whose WM_TIMER messages are processed not by the main window procedure but by an application-defined callback function, as in the following code sample, which creates a timer and uses the callback function MyTimerProc to process the timer's WM_TIMER messages.
// Set the timer.
SetTimer(hwnd, // handle of main window
IDT_TIMER3, // timer identifier
5000, // 5-second interval
(TIMERPROC) MyTimerProc); // timer callback
The calling convention for MyTimerProc must be based on the TimerProc callback function.
If your application creates a timer without specifying a window handle, your application must monitor the message queue for WM_TIMER messages and dispatch them to the appropriate window.
HWND hwndTimer; // handle of window for timer messages
MSG msg; // message structure
while (GetMessage(&msg, // message structure
NULL, // handle of window to receive the message
NULL, // lowest message to examine
NULL)) // highest message to examine
{
// Post WM_TIMER messages to the hwndTimer procedure.
if (msg.message == WM_TIMER)
{
msg.hwnd = hwndTimer;
}
TranslateMessage(&msg); // translates virtual-key codes
DispatchMessage(&msg); // dispatches message to window
}