关于定时器timeSetEvent

控制台程序演示

 

#include <iostream>
#include <Windows.h>
#include <MMSystem.h>
#pragma comment(lib, "winmm.lib")
using namespace std;
#define TIME_USER 2000     // 时间间隔,毫秒为单位
#define TIMER_ACCURACY 1 // 定义时钟分辨率,毫秒为单位

//------------------------------------------------------------------------------
void CALLBACK timerProc(UINT uTimerID, UINT uMsg,DWORD dwUser,
       DWORD dwl,DWORD dw2);

//==============================================================================
class CTimer
{
public:
 CTimer();
 ~CTimer();
 /// 定时处理
 void startTimer();
private:
 UINT m_nTimerInterval; // 定义时间间隔
 UINT m_nAccuracy;  // 定义分辨率
 UINT m_nTimerHandle; // 定义定时器句柄
};

CTimer::CTimer():
m_nTimerInterval(TIME_USER)
{
 TIMECAPS tc;
 // 利用函数timeGetDeVCaps取出系统分辨率的取值范围,如果无错则继续
 if(timeGetDevCaps(&tc,sizeof(TIMECAPS))==TIMERR_NOERROR)
 {
  m_nAccuracy=min(max(tc.wPeriodMin, TIMER_ACCURACY),tc.wPeriodMax); //分辨率的值不能超出系统的取值范围
  // 调用timeBeginPeriod函数设置定时器的分辨率
  timeBeginPeriod(m_nAccuracy);
     // 设置定时器
  startTimer();
 }
}

CTimer::~CTimer()
{
 cout<<"结束定时"<<endl;
 timeKillEvent(m_nTimerHandle); // 删除定时器
 timeEndPeriod(m_nAccuracy);
}


// 定时器
void CTimer::startTimer()

 m_nTimerHandle = timeSetEvent(m_nTimerInterval,m_nAccuracy,(LPTIMECALLBACK)timerProc,(DWORD)this,TIME_PERIODIC);
}

//------------------------------------------------------------------------------
void CALLBACK timerProc(UINT uTimerID, UINT uMsg,DWORD dwUser,DWORD dwl,DWORD dw2)
{
 // 定义计数器
 static int ms = 1;
 
 static DWORD oldTime = GetTickCount();
 static DWORD newTime = 0;
 newTime = GetTickCount();

 // 事件间隔的毫秒数
 DWORD milliseconds = newTime - oldTime;

 LARGE_INTEGER m,n,k;
 QueryPerformanceCounter(&m);
 QueryPerformanceFrequency(&n);

 k.QuadPart = 1;

 // 输出
 cout<<"occured..."<<endl
  <<ms<<" *** "<<milliseconds<<" *** "<<m.QuadPart/n.QuadPart/k.QuadPart  //[事件次数,毫秒级间隔,时钟时间经过]
  <<endl<<endl;
 
 ms++;
 oldTime = newTime;
}

//==============================================================================
int main()
{
 CTimer obj;

 int nWait;
 cin>>nWait;
 return 0;
}

你可能感兴趣的:(timer,user,Integer,Class,callback)