1.SetTimer:在控制台应用程序中同样可以用SetTimer实现定时器的效果。
普通的win32程序中定时器的应用很多也很方便,但是在win32控制台中也是可以使用定时器的,利用的是windows程序的消息循环机制,如下:
#include<iostream> #include<windows.h> using namespace std; //定时器ID DWORD dwTimerId = 0; void CALLBACK TimeProc( HWND hwnd, UINT message, UINT idTimer, DWORD dwTime) { if (dwTimerId == idEvent) { cout<<"触发定时器!"<<endl; } } int main() { //必须用消息循环,否则Timer无效 //返回值位定时器ID,而不是参数1 dwTimerId = SetTimer(NULL,1,1000,TimeProc); MSG msg; while(GetMessage(&msg,NULL,0,0)) { if(msg.message==WM_TIMER) { DispatchMessage(&msg); } } return 0; }
#include <windows.h> #include <stdio.h> #include <conio.h> int count =0; DWROD dwTimerId = 0; VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { if (dwTimerId == idEvent) { 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); dwTimerId = 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 = 0; printf("use timer in workthread of console application\n"); HANDLE hThread = CreateThread(NULL,0,Thread,0,0,&dwThreadId); getch(); return 0; }
函数: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(); }