控制台程序中使用定时器

9 篇文章 0 订阅

转1

我现在项目是一个控制台程序,用到的Win32API都是与界面无关的,今天需要加入定时器刷新的功能,由于没有消息循环,所以WM_TIMER消息应该如何处理呢?综合了下网上找到的资料,写了个简单的demo,个人以为这种在一个线程中创建定时器,再通过指定的回调函数来处理定时器触发的模式是比较好的。


#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,3000,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;
}




作者:洞庭散人

出处:http://phinecos.cnblogs.com/   


GetTickCount可以到18-20ms精度 
timeGetTime可以到1ms精度  

QueryPerformanceFrequency 配合 QueryPerformanceCounter可以做到很高的精度 


#include <windows.h>
#include <iostream>

//after call MyTimeProce MAX_TIMER_CALLED times, kill the timer and quit the application 
const int MAX_TIMER_CALLED = 100;

//timer procedure
void CALLBACK MyTimerProc( HWND hwnd, UINT uMsg,UINT_PTR idEvent,DWORD dwTime );

//console application entry point
int main()
{
   // Set the timer. 
   UINT_PTR IDT_TIMER = 1;             // timer identifier
   SetTimer( NULL,                     // handle to main window 
             IDT_TIMER,                // timer identifier 
             100,                     // 1-second interval 
             (TIMERPROC) MyTimerProc); // timer callback



   // we need a message loop to deal with the timer event
   MSG msg;
   while (GetMessage(&msg, NULL, 0, 0))
   {
      TranslateMessage(&msg); 
      DispatchMessage(&msg);  
   }

   return 0;
}

// implementation of MyTimerProc
void CALLBACK MyTimerProc( HWND hwnd, UINT uMsg,UINT_PTR idEvent,DWORD dwTime )
{
   static int nCalled = 0;
   ++nCalled;
   std::cout << "MyTimerProc called " << nCalled << " times" << std::endl;
   
   if ( nCalled >= MAX_TIMER_CALLED ) {
      KillTimer(hwnd, idEvent);            // kill the timer
      PostMessage(NULL, WM_QUIT, 0, 0);    // quit the application
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值