Timers allow an application to perform an action at regular intervals without blocking the execution of the rest of the program. A timer is created using the SetTimer() function. Once created, the timer continues to generate timer events until it is destroyed or the application terminates.

The prototype for the function is:

UINT_PTR SetTimer(
    HWND      hWnd,
    UINT_PTR  nIDEvent,
    UINT      uElapse,
    TIMERPROC lpTimerFunc );

 

UINT_PTR SetTimer(HWND hWnd,UINT  ID,UINT uElapse,TIMERPROC lpTimerFunc);
 

Parameters

hWnd
A handle to the window associated with the timer.

nIDEvent
An application-defined identifier for the timer.

uElapse
The time interval, in milliseconds, between timer events.

lpTimerFunc
A pointer to an application-defined TIMERPROC callback function. If this parameter is NULL, the system posts a WM_TIMER message to the window's message queue whenever the timer expires. If a callback function is specified, Windows calls the callback function each time the timer expires instead of posting a WM_TIMER message.

If the function succeeds, the return value is a timer identifier. If the function fails, the return value is 0.

The SetTimer() function can also modify an existing timer. To update a timer, specify the same window handle and timer identifier. The timer interval can then be changed, and a message-based timer can be converted into a callback timer (or vice versa) by changing the lpTimerFunc parameter.

A timer is destroyed using the KillTimer() function. Its prototype is:

BOOL KillTimer(
    HWND     hWnd,
    UINT_PTR uIDEvent
);

Parameters

hWnd
A handle to the window associated with the timer.

uIDEvent
The identifier of the timer to be destroyed.

If the function succeeds, the return value is non-zero. If the function fails, the return value is 0.

Note: Windows timers are intended for general-purpose timing and user interface tasks. They are not high-precision timers, and the interval specified by uElapse is the minimum delay before a timer event is generated. The actual interval may be longer depending on system load and the scheduling of Windows.

Example

The following short program creates a digital clock using the timer function to update the display

Display Code