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

 #include   <windows.h>
#include   <windows.h>    #include   <stdio.h>
#include   <stdio.h>    #include   <conio.h>
#include   <conio.h>   
 int   count   =0;
int   count   =0;   
 VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime) {
{ count++;
    count++;    printf("WM_TIMER   in   work   thread   count=%d\n",count);
    printf("WM_TIMER   in   work   thread   count=%d\n",count);    }
}
 DWORD CALLBACK   Thread(PVOID   pvoid)
DWORD CALLBACK   Thread(PVOID   pvoid)    {
{    MSG  msg;
    MSG  msg;    PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);
    PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);    UINT  timerid=SetTimer(NULL,111,3000,TimerProc);
    UINT  timerid=SetTimer(NULL,111,3000,TimerProc);    BOOL  bRet;
    BOOL  bRet;    
     while(   (bRet = GetMessage(&msg,NULL,0,0))!=   0)
    while(   (bRet = GetMessage(&msg,NULL,0,0))!=   0)    {
    {      if(bRet==-1)
        if(bRet==-1)    {
        {    //   handle   the   error   and   possibly   exit
            //   handle   the   error   and   possibly   exit    }
        }    else
        else    {
        {     TranslateMessage(&msg);
            TranslateMessage(&msg);      DispatchMessage(&msg);
            DispatchMessage(&msg);      }
        }    }
    }    KillTimer(NULL,timerid);
    KillTimer(NULL,timerid);    printf("thread   end   here\n");
    printf("thread   end   here\n");    return   0;
    return   0;    }
}
 int    main()
int    main()    {
{    DWORD   dwThreadId;
    DWORD   dwThreadId;    printf("use   timer   in   workthread   of   console   application\n");
    printf("use   timer   in   workthread   of   console   application\n");    HANDLE   hThread  =    CreateThread(NULL,0,Thread,0,0,&dwThreadId);
    HANDLE   hThread  =    CreateThread(NULL,0,Thread,0,0,&dwThreadId); _getch();
    _getch();  return 0;
    return 0; }
}   


作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2008-03-08 17:52 Phinecos(洞庭散人) 阅读(7043) 评论(9) 收藏 举报
 
                    
                     
                    
                 
                    
                

 
     
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号 
