Your browser doesn't support JavaScript Timers - Windows Programming

Timers

Timers are used to schedule a periodic event and execute some program code. The CWnd member function SetTimer() initiates a timer to fire at specified intervals and CWnd member function KillTimer() stops the timer. A timer notifies an application that a time interval has elapsed in one of two ways:

By sending a WM_TIMER message to a specified window
By calling an application-defined callback function

The prototype for the CWndSetTimer is

UINT SetTimer( UINT nIDEvent, UINT nElapse, lpfnTimer);

where
nIDEvent – Specifies a timer identifier. Must not be zero
nNElapse – Specifies the time-out value, in milliseconds.
lpfnTimer – Specifies the address of the application-supplied TimerProc callback function that processes the WM_TIMER messages. If this parameter is NULL, the WM_TIMER messages are placed in the application’s message queue and handled by the CWnd object.

Returns the timer identifier if the function is successful.

As an example

SetTimer (1, 700, NULL);

Assigns a timer ID of 1, and sends WM_TIMER message to the window whose SetTimer function was called every 700 milliseconds. The final NULL parameter configures the timer to send WM_TIMER messages rather than call a callback function

Responding to WM_TIMER Messages

MFC’s ON_WM_TIMER message-map macro responds to WM_TIMER messages by a call to the member function OnTimer. OnTimer is prototyped as follows:

afx_msg void OnTimer (UINT nTimerID)

where nTimerID is the ID of the timer that generated the message.

Setting a Timer to respond to a callback function

To set a timer that uses a callback, the 3rd parameter of the SetTimer function must be set to the name of the callback function as follows

SetTimer (ID_TIMER, 500, TimerCallBackProc)

The callback procedure is prototyped as follows:

void CALLBACK TimerCallBackProc (HWND hWnd, UINT nMsg, UINT nTimerID, DWORD dwTime)

where
hWnd contains the window handle,
nMsg contains the message ID WM_TIMER,
nTimerID holds the timer ID,
dwTime specifies the number of milliseconds that have elapsed since Windows was started.

Stopping a Timer

To stop a timer call the CWnd member function KillTimer, which stops a timer and stops the WM_TIMER messages or timer callbacks. The following statement releases the timer with ID is 1:

KillTimer (1);

Example

The following program illustrates a simple timer app by flashing a “hello world” message in the top left-hand corner of the window

Download Code