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

None.gif
None.gif#include   
<windows.h>   
None.gif#include   
<stdio.h>   
None.gif#include   
<conio.h>   
None.gif
None.gif
int   count   =0;   
None.gif
None.gifVOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    count
++;   
InBlock.gif    printf(
"WM_TIMER   in   work   thread   count=%d\n",count);   
ExpandedBlockEnd.gif}

None.gif
None.gifDWORD CALLBACK   Thread(PVOID   pvoid)   
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{   
InBlock.gif    MSG  msg;   
InBlock.gif    PeekMessage(
&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);   
InBlock.gif    UINT  timerid
=SetTimer(NULL,111,3000,TimerProc);   
InBlock.gif    BOOL  bRet;   
InBlock.gif    
InBlock.gif    
while(   (bRet = GetMessage(&msg,NULL,0,0))!=   0)   
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{     
InBlock.gif        
if(bRet==-1)   
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{   
InBlock.gif            
//   handle   the   error   and   possibly   exit   
ExpandedSubBlockEnd.gif
        }
   
InBlock.gif        
else   
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    
InBlock.gif            TranslateMessage(
&msg);     
InBlock.gif            DispatchMessage(
&msg);     
ExpandedSubBlockEnd.gif        }
   
ExpandedSubBlockEnd.gif    }
   
InBlock.gif    KillTimer(NULL,timerid);   
InBlock.gif    printf(
"thread   end   here\n");   
InBlock.gif    
return   0;   
ExpandedBlockEnd.gif}

None.gif
None.gif
int    main()   
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{   
InBlock.gif    DWORD   dwThreadId;   
InBlock.gif    printf(
"use   timer   in   workthread   of   console   application\n");   
InBlock.gif    HANDLE   hThread  
=    CreateThread(NULL,0,Thread,0,0,&dwThreadId);
InBlock.gif    _getch(); 
InBlock.gif    
return 0;
ExpandedBlockEnd.gif}
   
None.gif
None.gif
None.gif