#.h
#include <Windows.h>
#include <stdio.h>
typedef void (*CALLFINC)();
class MClock
{
private:
MClock();
~MClock();
public:
//获取类指针
static MClock* GetInterFace();
//创建定时器
void StartClock(UINT clock);
//定时器执行函数
void UpData();
//销毁定时器
void DelClock(UINT &timerID);
//设置函数指针
void SetFun(CALLFINC ptr);
//获取时钟ID
int GetTimerID();
protected:
CALLFINC m_func;
int m_TimerID;
static MClock* m_MClockPtr;
};
#cpp
#include "MClock.h"
void CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nTimerid, DWORD dwTime);
MClock* MClock::m_MClockPtr = nullptr;
void CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nTimerid, DWORD dwTime)
{
MClock::GetInterFace()->UpData();
}
MClock::MClock()
{
m_TimerID = -1;
}
MClock::~MClock()
{
}
MClock* MClock::GetInterFace()
{
if (m_MClockPtr == nullptr)
{
m_MClockPtr = new MClock;
}
return m_MClockPtr;
}
void MClock::StartClock(UINT clock)
{
/*
参数一: 窗口句柄
参数二: 定时器ID,多个定时器时,可以通过该ID判断是哪个定时器
参数三: 时间间隔,单位为毫秒
参数四: 回调函数
*/
MSG msg;
m_TimerID = SetTimer(NULL, 1, clock, (TIMERPROC)TimerProc);
while (GetMessage(&msg, NULL, NULL, NULL))
{
if (msg.message == WM_TIMER)
{
TranslateMessage(&msg);///TranslateMessage函数将虚拟键消息转换成字符消息
/*该函数调度一个消息给窗口程序。通常调度从GetMessage取得的消息。
消息被调度到的窗口程序即是MainProc()函数*/
DispatchMessage(&msg);
//break; //此处最好有一个这个,不然貌似Killtimer结束不了定时器的样子.
}
}
}
void MClock::UpData()
{
//TODIO: 定时器执行函数
if(m_func!=nullptr)
m_func();
}
void MClock::DelClock(UINT &timerID)
{
KillTimer(NULL, timerID);
}
void MClock::SetFun(CALLFINC ptr)
{
m_func = ptr;
}
int MClock::GetTimerID()
{
return m_TimerID;
}