使用Windows的多媒体定时器,可以实现高精度的定时
// 在输入库中,添加Winmm.lib
// lpTimePro函数的原型为:
// static void PASCAL OnTimerProc(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2);
#pragma once
#include
#include
class CMMTimer
{
public:
CMMTimer(void);
~CMMTimer(void);
bool Start(unsigned int uTime, LPTIMECALLBACK lpTimeProc, void* pParam);
void Stop();
private:
UINT m_TimerID;
UINT m_wAccuracy;
};#include "MMTimer.h"
CMMTimer::CMMTimer(void) : m_TimerID(NULL), m_wAccuracy(0)
{
}
CMMTimer::~CMMTimer(void)
{
Stop();
}
bool CMMTimer::Start(unsigned int uTime, LPTIMECALLBACK lpTimeProc, void* pParam)
{
TIMECAPS tc;
if(timeGetDevCaps(&tc,sizeof(TIMECAPS))!=TIMERR_NOERROR)
{
return false;
}
m_wAccuracy = min(max(tc.wPeriodMin, 1), tc.wPeriodMax);
timeBeginPeriod(m_wAccuracy);
m_TimerID = timeSetEvent(uTime, m_wAccuracy, (LPTIMECALLBACK)lpTimeProc, (DWORD_PTR)pParam, TIME_PERIODIC);
return (m_TimerID != NULL);
}
void CMMTimer::Stop()
{
if(m_TimerID != NULL)
{
timeKillEvent(m_TimerID);
timeEndPeriod(m_wAccuracy);
m_wAccuracy = 0;
m_TimerID = NULL;
}
}