前进的道路不是一帆风顺的,要随时迎接挑战,敢于战胜困难!

坚持一下,找人聊聊天,释放一些压力!

 

Win32控制台程序的定时器实现(转载)

在控制台中使用定时器不能简单的SetTimer了事,这在控制台里这种SetTimer的方式是有点麻烦的,需要自己写消息循环投递WM_TIMER消息。其实在控制台里可以使用多媒体时钟来计时: 

example: 

//启动计时器 
MMRESULT nIDTimerEvent = timeSetEvent( 
  1000,//延时1秒 
   0, 
  TimeProc, 
  0, 
  (UINT)TIME_PERIODIC); 
if( nIDTimerEvent == 0 ) 
  cout<<"启动计时器失败"<<endl; 


//回调过程(时钟到来,回调函数被系统自动调用) 
void CALLBACK TimeProc( 
  UINT uID,       
  UINT uMsg,     
  DWORD dwUser,   
  DWORD dw1,     
  DWORD dw2       


  cout<<"时钟到来"<<endl; 
   

 
当然了,你要是习惯于SetTimer,那就用SetTimer吧:
下面是我在Console下用SetTimer写的一个例子:
#include <windows.h>
#include <iostream>
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<<"a timer comming"<<endl;
}

posted on 2009-01-07 11:08  山径山精  阅读(1097)  评论(2编辑  收藏  举报

导航