1. 使用windows api函数SetTimer设定计时器
UINT_PTR SetTimer(
HWND hWnd, // 窗口句柄
UINT_PTR nIDEvent, // 定时器ID,多个定时器时,可以通过该ID判断是哪个定时器
UINT uElapse, // 时间间隔,单位为毫秒
TIMERPROC lpTimerFunc // 回调函数
);
//如果已传入参数nIDEvent,则函数的返回值与nIDEvent相同,如果参数nIDEvent为NULL,则函数的返回值为系统为这
//个定时器设定的一个ID
注意:设置第二个参数时要注意,如果设置的等待时间比处理时间短,程序可能会出现问题。
2. 编写Timer的回调函数
void CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nTimerid, DWORD dwTime);
//hWnd: 与SetTimer中所传入的hWnd一致
//nMsg: WM_TIMER消息
//nTimerid: 计时器编号
//dwTime: 从系统启动到现在的时间(用毫秒表示),这是由GetTickCount函数所返回的
3. 在使用完计时器后必须调用“KillTimer(NULL, iTimerID)”来销毁计时器
Sample code
#include <iostream>
#include <windows.h>
void CALLBACK TimerProc(HWND hwnd, UINT Msg, UINT idEvent, DWORD dwTime);
int main()
{
UINT timerId = 1;
MSG msg;
// int n = GetMessage(&msg, NULL, NULL, NULL); //Wait for message, block the thread when getting no message
SetTimer(NULL, timerId, 1000, TimerProc); //每间隔1000毫秒定时器发送 一条信息,并执行回调函数中的代码
int nTemp;
while ((nTemp = GetMessage(&msg, NULL, NULL, NULL)) && (-1 != nTemp) && (0 != nTemp))
{
if (WM_TIMER == msg.message)
{
cout << "I got a message" << endl;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
void CALLBACK TimerProc(HWND hwnd, UINT Msg, UINT idEvent, DWORD dwTime)
{
cout << "HelloWorld" << endl;
}