在win32控制台应用程序中实现定时器

1. SetTimer: 在控制台应用程序中同样可以用 SetTimer 实现定时器的效果。
示例代码:

#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。   Windows多媒体高精度定时器。
函数: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(); }

注:这段代码在dev c++下无法编译运行,在visual studio 2010下可以运行通过。

4. clock。 用于延迟显示。

#include <stdio.h> #include <time.h> #include<windows.h> int main(void) { clock_t start, end; start = clock(); Sleep(2000); end = clock(); printf("The time was: %d\n", (end - start) / CLK_TCK);//注意是%d system("pause"); return 0; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值