Programming Windows - Timers


Home | API | MFC | C++ | C | Previous | Next

Timers are used to schedule a periodic event and execute some program code. The SetTimer() API function creates a timer and sets its parameters. Once a timer is created, it will generate timer events until the timer is terminated or the application exits. The prototype of this function is

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

hWnd – a handle to the window to be associated with the timer..
iD – specifies an id value associated with the timer.
uElapse – Sets the time between interrupts in milliseconds.
lpTimerFunc - If lpTimerFunc is NULL, the system posts a WM_TIMER message to the application queue. If a function is specified the system directly calls an application-defined TIMERPROC callback function for each timer event.

If the function succeeds, the return value is an integer identifying the new timer. If the function fails to create a timer, the return value is zero

The SetTimer function also allows a timer’s parameters to be amended. Both the window handle and the timer identifier must be specified when modifying an existing timer. SetTimer can also change a message-based timer into a callback timer. To terminate a timer use the KillTimer() function. The prototype is

BOOL KillTimer(HWND hWnd,UINT_PTR uIDEvent);

Where
HWnd is a handle to the window associated with the specified timer.
UINT_PTR is the identifier of the timer to be destroyed.

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

Example

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


Home | API | MFC | C++ | C | Previous | Next

Creating a Simple Window | Common Elements | Data Types and Character Sets | The Device Context | Graphics Device Interface | Displaying Text | Displaying Graphics | Mapping Modes | Keyboard Input | Working with the Mouse | Menus | Child Windows | The Dialog Box | Windows Message Box | Common Dialog Box | Bitmaps | Common Controls | Creating a Toolbar | Multiple Document Interface | Timers | DLL’s | Creating Custom Controls | Owner Drawn Controls | API Hooking and DLL Injection | File Management Functions | String Manipulation | System Information Functions

Last Updated: 15 September 2022