MMRESULT timeSetEvent( UINT uDelay,
UINT uResolution,
LPTIMECALLBACK lpTimeProc,
WORD dwUser,
UINT fuEvent )
uDelay:以毫秒指定事件的周期。
Uresolution:以毫秒指定延时的精度,数值越小定时器事件分辨率越高。缺省值为1ms。
LpTimeProc:指向一个回调函数。
DwUser:存放用户提供的回调数据。
FuEvent:指定定时器事件类型:
TIME_ONESHOT:uDelay毫秒后只产生一次事件
TIME_PERIODIC :每隔uDelay毫秒周期性地产生事件。
/
关于这个函数的作用以及使用方法,网上也有很多相关的介绍,但是自己在使用 的时候还是碰到了好多问题,不断的出现各种error,不断的调试,在折腾了好久以后,终于可以运行了。这里把我折腾的历程写出来,希望跟我有类似经历的人能少走弯路。(我是一个小小小菜鸟……)
1,这是一个c环境下可以实现的例子。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma comment(lib,"Winmm.lib")
#define ONE_MILLI_SECOND 1 //定义1ms和2s时钟间隔,以ms为单位 ;
#define TWO_SECOND 2000
#define TIMER_ACCURACY 1 //定义时钟分辨率,以ms为单位
void PASCAL OneMilliSecondProc(UINT wTimerID, UINT msg, DWORD dwUser, DWORD dwl,
DWORD dw2)
{
printf("11111111111\n");
exit(0);
}
void main()
{
HANDLE hHandle;
UINT wTimerRes_1ms, wTimerRes_2s; //定义时间间隔
UINT wAccuracy; //定义分辨率
UINT TimerID_1ms, TimerID_2s; //定义定时器句柄
wTimerRes_1ms = 5000;
if ((TimerID_1ms = timeSetEvent(wTimerRes_1ms, wAccuracy, (LPTIMECALLBACK)
OneMilliSecondProc, // 回调函数
(DWORD)(1), // 用户传送到回调函数的数据;
TIME_PERIODIC)) == 0)
//周期调用定时处理函数
{
printf("start!!!!!!!!!!!\n");
}
else
{
printf("end!!!!!!!!!!!\n");
}
while (1)
{
printf("hello!\n");
Sleep(1000);
}
}
2,我当时是希望在MFC环境下实现一个 计时器 功能,我照搬了上面的代码,但是发现出现了错误
error C2440: 'type cast' : cannot convert from '' to 'void (__stdcall *)(unsigned int,unsigned int,unsigned long,unsigned long,unsigned long)'
None of the functions with this name in scope match the target type
或者
error C2664: 'timeSetEvent' : cannot convert parameter 3 from 'void (unsigned int,unsigned int,unsigned long,unsigned long,unsigned long)' to 'void (__stdcall *)(unsigned int,unsig
ned int,unsigned long,unsigned long,unsigned long)'
,查看网上的说明,发生上述错误的原因是因为在MFC下面的类成员函数中调用回调函数时,应将回调函数设成static静态函数,原因是因为普通的C++成员函数都有一个隐含的“this”指针,以作为参数使得其他成员函数可以访问该成员函数以及数据成员。因为静态函数不使用“this”指针,因此可以作为回调函数了。
因此在MFC中,在头文件中申明回调函数:static void CALLBACK TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);然后再cpp文件中定义该回调函数:
void CALLBACK TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);
{
……
}
但是我运行以后,还是出现了error C2597: illegal reference to data member 'CxxxView::xxx' in a static member function。这个是因为我在设置为静态函数的回调函数里调用了类数据成员,在静态函数里调用非静态成员就会出现问题。
因此利用 TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)里的dwUser给函数传递一个指针:
void CALLBACK CxxxView::TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
{
CxxxMy3DEYEView* pView = (CxxxView*)dwUser;
pView->类数据成员;
pView->类数据成员;
}