//StdAfx.h
<span style="font-family: Arial, Helvetica, sans-serif;">#pragma once</span>
#include <easyx.h>
#include <time.h>
#include <stdio.h>
</pre>//TimerUtils.h<p></p><pre code_snippet_id="590181" snippet_file_name="blog_20150127_5_6910356" name="code" class="cpp">///
// 计时器声明
//
#ifndef _TIMER_UTILS
#define _TIMER_UTILS
#include "StdAfx.h"
class Timer
{
public:
Timer();
Timer(UINT interval, bool loop, TIMERPROC TimerProc);
~Timer();
int start(); //启动计时器
int updata(); //刷新计时器记录的时间点
int pause(); //暂停计时器(返回剩余毫秒数)
int unpause(); //取消暂停计时器(返回剩余毫秒数)
int destroy(); //清除计时器
UINT getIndex() const; //获取计时器ID
UINT getInterval() const; //获取计时器计时间隔
UINT getRemain() const; //获取计时器剩余时间
bool isLoop() const; //判断计时器是否循环
bool isPaused() const; //判断计时器是否处于暂停状态
TIMERPROC getTimerProc() const; //获取计时器回调函数
private:
UINT Index; //计时器ID
UINT Interval; //计时间隔
UINT BeginClock; //计时器开始时的时间点
UINT Remain; //剩余时间
bool Loop; //循环状态
bool Paused; //暂停状态
TIMERPROC funcTimerProc;//回调函数
};
#endif
//TimerUtils.cpp
///
// 计时器实现
//
#include "TimerUtils.h"
Timer* pTimerList[12800];
UINT nCount = 0;
//无参构造
Timer::Timer()
{
this->Index = nCount;
this->Interval = 1;
this->Loop = false;
this->Paused = false;
this->Remain = this->Interval;
this->funcTimerProc = NULL;
pTimerList[nCount] = this;
nCount++;
}
//含参构造
Timer::Timer(UINT interval, bool loop, TIMERPROC funcTimerProc)
{
this->Index = nCount;
this->Interval = interval;
this->Loop = loop;
this->Paused = false;
this->Remain = this->Interval;
this->funcTimerProc = funcTimerProc;
pTimerList[nCount] = this;
nCount++;
}
//析构
Timer::~Timer()
{
pTimerList[this->Index] = NULL;
}
bool Timer::isLoop() const
{
return this->Loop;
}
bool Timer::isPaused() const
{
return this->Paused;
}
UINT Timer::getIndex() const
{
return this->Index;
}
UINT Timer::getInterval() const
{
return this->Interval;
}
UINT Timer::getRemain() const
{
return this->Remain;
}
TIMERPROC Timer::getTimerProc() const
{
return this->funcTimerProc;
}
int Timer::start()
{
this->Remain = this->Interval;
if (this->Paused)
{
this->unpause();
}
else
{
this->updata();
SetTimer(GetHWnd(), this->Index, this->Interval, this->funcTimerProc);
}
return 0;
}
int Timer::updata()
{
this->BeginClock = clock();
return 0;
}
int Timer::pause()
{
UINT temp = clock();
this->Paused = true;
this->Remain = this->Remain - (temp - this->BeginClock);
KillTimer(GetHWnd(), this->Index);
return this->Remain;
}
int Timer::unpause()
{
if (this->Paused)
{
this->Paused = false;
this->updata();
printf("%p %d %d %p\n", GetHWnd(), Index, Remain, funcTimerProc);
if (this->Remain < 15)
{
funcTimerProc(GetHWnd(), WM_TIMER, this->Index, (DWORD)time(NULL));
}
else
{
SetTimer(GetHWnd(), this->Index, this->Remain, this->funcTimerProc);
}
}
return 0;
}
int Timer::destroy()
{
KillTimer(GetHWnd(), this->Index);
delete this;
return 0;
}
|