示例代码:
#include<iostream> #include<windows.h> using namespace std; void CALLBACK TimeProc( HWND hwnd, UINT message, UINT idTimer, DWORD dwTime); int main() { SetTimer(NULL,1,1000,TimeProc); MSG msg; while(GetMessage(&msg,NULL,0,0)) { if(msg.message==WM_TIMER) { DispatchMessage(&msg); } } return 0; } void CALLBACK TimeProc( HWND hwnd, UINT message, UINT idTimer, DWORD dwTime) { cout<<"触发定时器!"<<endl; }此程序每过一秒显示一次“触发定时器!”。
2.线程+SetTimer:网上牛人用线程做的相同效果
#include <windows.h> #include <stdio.h> #include <conio.h> int count =0; VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime) { count++; printf("WM_TIMER in work thread count=%d\n",count); } DWORD CALLBACK Thread(PVOID pvoid) { MSG msg; PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE); UINT timerid=SetTimer(NULL,111,1000,TimerProc); BOOL bRet; while( (bRet = GetMessage(&msg,NULL,0,0))!= 0) { if(bRet==-1) { // handle the error and possibly exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } } KillTimer(NULL,timerid); printf("thread end here\n"); return 0; } int main() { DWORD dwThreadId; printf("use timer in workthread of console application\n"); HANDLE hThread = CreateThread(NULL,0,Thread,0,0,&dwThreadId); getch(); return 0; }3.timeSetEvent。
函数:MMRESULT timeSetEvent( UINT uDelay,
UINT uResolution,
LPTIMECALLBACK lpTimeProc,
WORD dwUser,
UINT fuEvent )
说明:
uDelay:以毫秒指定事件的周期。
Uresolution:以毫秒指定延时的精度,数值越小定时器事件分辨率越高。缺省值为1ms。
LpTimeProc:指向一个回调函数。
DwUser:存放用户提供的回调数据。
FuEvent:指定定时器事件类型:
TIME_ONESHOT:uDelay毫秒后只产生一次事件
TIME_PERIODIC :每隔uDelay毫秒周期性地产生事件。
#include<iostream> #include<windows.h> #include <Mmsystem.h> #pragma comment(lib, "winmm.lib") using namespace std; void CALLBACK TimeProc( UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2 ) { cout<<"定时器触发!"<<endl; } int main() { timeSetEvent( 1000,0, TimeProc, 0, (UINT)TIME_PERIODIC); getchar(); }