Timer Support for Non-Window Classes

Recently I had to create a proprietary communication protocol stack to provide a link to custom hardware. During this task Ive encoutered a problem. I needed a timer. Windows provides you timers through SetTimer() function or through CWnd::SetTimer() function. In both cases, your class must be a window to use the timer. I did not have the luxury, so I created my own class that provides timer support to non- window objects. I use VC++ with MFC.

All you have to do is to derive your class from CtimerSupport class and then you can use CtimerSupport::SetTimer() and CtimerSupport::KillTimer() functions. And you have to override virtual function OnTimer(UINT nTimerID);

You will also have to override handler for WM_TIMER message in your main window. Sample handler will look like:


/**********************************************************
 * Module:    Handler to process WM_TIMER message
 *
 * Parameters:  nIDEvent  - Timer that expired
 * Returns:   none
 * Globals:   none
 *  
 **********************************************************
 */

void CMainFrame::OnTimer(UINT nIDEvent) 
{
 // Call appropriate handler
 ((STimerInfo *)nIDEvent)->pObject->OnTimer(nIDEvent);
  
 CFrameWnd::OnTimer(nIDEvent);
}

The idea behind the CtimerSupport class is to use main window as a mechanism to manipulate timers, but hide it from the rest of the code.

To start a timer in your code use SetTimer (UINT nTimerEvent, UINT nElapse), where nTimerEvent is user-defined event serving to identify the timer if multiple timers are used. NElapse is timer duration in ms.

SetTimer() returns 32-bit timer ID. This must be stored for future referencing to the timer.

Use KillTimer(UINT nTimerID) to stop the timer. nTimerID is the value returned by SetTimer().

OnTimer(UINT nTimerID) is called when timer expires. NTimerID is the value returned by the SetTimer(). You can get user-defined event out of timer ID by calling GetTimerEvent (UINT nTimerID). Thus, timers are differentiated by their Ids and/or by the user-defined event.

Notes

  1. Timers are continuous. If timer is not stopped by KillTimer() it will continue to generate calls to OnTimer(). If you want one-shot timer, call KillTimer() in the OnTimer() routine.
  2. Timer events are stacked. If timer expiration was not processed before timer expires again, two consecutive calls to OnTimer() will be made. Killing the timer does not clear the message queue, so any outstanding timer events will be processed, even if timer is stopped.

Downloads

Download source - 3 Kb