VC++控制台程序中使用定时器

      我现在项目是一个控制台程序,用到的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;
}
   


posted on   Phinecos(洞庭散人)  阅读(7018)  评论(9编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

统计

点击右上角即可分享
微信分享提示