
Introduction
In many of the programs we write, we need to know when a certain amount of time has passed before doing something; we need timing information. In a Windows program, that often means using the WM_TIMER
message. Sometimes, however, we need something a little more accurate, something a little more finely grained.
One option is to use the multimedia timer. This timer can give us greater accuracy and resolution than WM_TIMER
messages. The CMMTimer
class encapsulates the Windows multimedia functions to make using the multimedia timer easy and painless.
The CMMTimer and CMMTimerListener classes
The CMMTimer
provides a set of methods for using the multimedia timer. Listed below are each method and a brief description of how to use it.
bool Start(UINT Delay, UINT Resolution);
void Stop();
void Reset();
bool IsRunning() const { return m_RunningFlag; }
void AttachListener(CMMTimerListener &Listener);
void DetachListener(CMMTimerListener &Listener);
void NotifyListeners();
DWORD GetTotalMilliseconds() const;
DWORD GetTotalSeconds() const;
DWORD GetTotalMinutes() const;
DWORD GetTotalHours() const;
DWORD GetCurrentMilliseconds() const;
DWORD GetCurrentSeconds() const;
DWORD GetCurrentMinutes() const;
DWORD GetCurrentHours() const;
DWORD GetCount() const;
static void GetDevCaps(LPTIMECAPS TimeCap);
In order to receive timing events from a CMMTimer
object, you will need to implement the CMMTimerListener
class and attach your class to the CMMTimer
object with the AttachListener
method. For every timing event, the CMMTimer
will notify all of its listeners that a timing event has occurred by calling the Update
method in the CMMTimerListener
objects.
Also, it's important to note that you must link to the winmm.lib before you can use the CMMTimer
class.
The CMMTimer Demo App
I've included a toy application to demonstrate using the CMMTimer
and CMMTimerListener
classes. This program has a simple animation sequence. The speed of the animation is determined by a CMMTimer
object. To start the animation, simply press the Start button, and to stop the animation press Stop. The speed can be adjusted by choosing from the settings listed in the Speed combo box.
Conclusion
Well, that's about it. I hope you find this class helpful when you need timing notification that's a little more accurate than what WM_TIMER
messages can give you. Please let me know if any improvements can be made to the design or if there are additional features that would make the class more useful.