A Class To Encapsulate MultiMedia Timers

本文介绍了一个简单的多媒体定时器类的实现,包括如何在项目中包含该类的头文件和实现文件,如何通过继承自定义定时器类并覆盖成员函数来控制定时器的行为,以及如何设置和启动定时器,同时提供了源代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This simple class encapsulates the multimedia timers. To use the class include mmTimers.cpp and mmTimers.h in your project. Link with winmm.lib. To use a timer derive a class from CMMTimers and override member timerProc. timerProc will be called when the timer goes off. Instantiate a variable of the new class. The parameter to the constructor is the timer resolution in ms. To start a timer call startTimer. The first parameter specifies the period of the timer in ms. The second parameter specifies whether the timer is a one shot or periodic timer. To stop a periodic timer call stopTimer.

This code was developed with Visual C++ 5.0 and has been tested on NT 4.0.

The source follows:

The header file, mmTimers.h

#ifndef ___multimedia_timers___
#define ___multimedia_timers___


#include 

 

class CMMTimers
{
public:
 CMMTimers(UINT resolution);
 virtual ~CMMTimers();

 UINT getTimerRes() { return timerRes; };

 bool startTimer(UINT period,bool oneShot);
 bool stopTimer();

 virtual void timerProc() {};

protected:
 UINT timerRes;
 UINT timerId;
};


#endif 

The source file, mmTimers.cpp

#include "StdAfx.h"
#include "mmTimers.h"


CMMTimers::CMMTimers(UINT resolution) : timerRes(0), timerId(0)
{
 TIMECAPS tc;

 if (TIMERR_NOERROR == timeGetDevCaps(&tc,sizeof(TIMECAPS)))
 {
  timerRes = min(max(tc.wPeriodMin,resolution),tc.wPeriodMax);
  timeBeginPeriod(timerRes);
 }
}


CMMTimers::~CMMTimers()
{
 stopTimer();
 if (0 != timerRes)
 {
  timeEndPeriod(timerRes);
  timerRes = 0;
 }
}


extern "C"
void CALLBACK internalTimerProc(UINT id, UINT msg,
DWORD dwUser, DWORD dw1, DWORD dw2)
{
 CMMTimers * timer = (CMMTimers *)dwUser;

 timer->timerProc();
}


bool CMMTimers::startTimer(UINT period,bool oneShot)
{
 bool  res = false;
 MMRESULT result;

 result = timeSetEvent(period, timerRes, internalTimerProc,
 (DWORD)this,oneShot ? TIME_ONESHOT : TIME_PERIODIC);
 if (NULL != result)
 {
  timerId = (UINT)result;
  res = true;
 }

 return res;
}


bool CMMTimers::stopTimer()
{
 MMRESULT result;

 result = timeKillEvent(timerId);
 if (TIMERR_NOERROR == result)
  timerId = 0;

 return TIMERR_NOERROR == result;

DownLoad Source - 1KB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值