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

#include<windows.h>
#include<stdio.h>
#include<conio.h>
intcount=0;
VOIDCALLBACKTimerProc(HWNDhwnd,UINTuMsg,UINT_PTRidEvent,DWORDdwTime)

{
count++;
printf("WM_TIMERinworkthreadcount=%d/n",count);
}
DWORDCALLBACKThread(PVOIDpvoid)

{
MSGmsg;
PeekMessage(&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);
UINTtimerid=SetTimer(NULL,111,3000,TimerProc);
BOOLbRet;
while((bRet=GetMessage(&msg,NULL,0,0))!=0)

{
if(bRet==-1)

{
//handletheerrorandpossiblyexit
}
else

{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(NULL,timerid);
printf("threadendhere/n");
return0;
}
intmain()

{
DWORDdwThreadId;
printf("usetimerinworkthreadofconsoleapplication/n");
HANDLEhThread=CreateThread(NULL,0,Thread,0,0,&dwThreadId);
_getch();
return0;
}

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
本文介绍了一个控制台程序如何实现定时器功能的方法。该程序利用Win32API中的SetTimer函数,并通过工作线程处理WM_TIMER消息,实现了定时任务的刷新。文章提供了一个简单示例,演示了如何在线程中创建定时器并指定回调函数处理定时事件。
736

被折叠的 条评论
为什么被折叠?



