您的位置:首页 > 其它

vc高精度多媒体定时器的使用方法

2013-10-11 15:53 399 查看
在VC编程中,用SetTimer可以定义一个定时器,到时间了,就响应OnTimer消息,但这种定时器精度太低了。如果需要精度更高一些的定时器(精确到1ms),可以使用下面的高精度多媒体定时器进行代码优化,可以达到毫秒级的精度,而且使用方便。先要包含头文件"mmsystem.h"和库文件"winmm.lib"。

vc高精度多媒体定时器的使用方法如下:

#include "mmsystem.h" //head file

#pragma comment(lib,"winmm") //lib file

const int timePeriod = 2;

const int timeRes = 1 ;

/*******************MMTimer fuction********************************\

CreateTimer : create a Multimedia timer

DestroyTimer: destroy a Multimedia timer

TimerHandler: the actual timer handler procedure

\******************************************************************/

/******************************************************************\

function

name : CreateTimer

desc : create a realtime timer

argument

void

ret code

[HANDLE] ,the handle of the timer

\******************************************************************/

UINT CMyTimer::CreateTimer()

{

//create the timer



// Create a periodic timer

timeBeginPeriod(timeRes);

timerID = timeSetEvent(

timePeriod,

timeRes,

TimerHandler,

(DWORD)this,

TIME_PERIODIC);



return timerID;

}

/******************************************************************\

function

name : DestroyTimer

desc : destroy the timer created by calling CreateTimer

argument

void

ret code

void

\******************************************************************/

void CMyTimer::DestroyTimer()

{

if ( bRun )

{

timeKillEvent(timerID);

timeEndPeriod(timeRes);

bRun = FALSE;

}

}

/******************************************************************\

function

name : TimerHandler

desc : timer procedure called when the the timer signaled

argument

dwUser,[in],user para data

ret code

void

\******************************************************************/

void CALLBACK CMyTimer::TimerHandler(UINT id, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)

{

CMyTimer* pThis = (CMyTimer*)dwUser;

}

使用多媒体定时器timeSetEvent()函数,该函数定时精度为ms级。利用该函数可以实现周期性的函数调用。函数的原型如下:

MMRESULT timeSetEvent( UINT uDelay,

UINT uResolution,

LPTIMECALLBACK lpTimeProc,

WORD dwUser,

UINT fuEvent )

该函数设置一个定时回调事件,此事件可以是一个一次性事件或周期性事件。事件一旦被激活,便调用指定的回调函数, 成功后返回事件的标识符代码,否则返回NULL。函数的参数说明如下:

uDelay:以毫秒指定事件的周期。

Uresolution:以毫秒指定延时的精度,数值越小定时器事件分辨率越高。缺省值为1ms。

LpTimeProc:指向一个回调函数。

DwUser:存放用户提供的回调数据。

FuEvent:指定定时器事件类型:

TIME_ONESHOT:uDelay毫秒后只产生一次事件

TIME_PERIODIC :每隔uDelay毫秒周期性地产生事件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: