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

我现在项目是一个控制台程序,用到的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.gifVOIDCALLBACKTimerProc(HWNDhwnd,UINTuMsg,UINT_PTRidEvent,DWORDdwTime)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifcount
++;
InBlock.gifprintf(
"WM_TIMERinworkthreadcount=%d/n",count);
ExpandedBlockEnd.gif}

None.gif
None.gifDWORDCALLBACKThread(PVOIDpvoid)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifMSGmsg;
InBlock.gifPeekMessage(
&msg,NULL,WM_USER,WM_USER,PM_NOREMOVE);
InBlock.gifUINTtimerid
=SetTimer(NULL,111,3000,TimerProc);
InBlock.gifBOOLbRet;
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
//handletheerrorandpossiblyexit
ExpandedSubBlockEnd.gif
}

InBlock.gif
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gifTranslateMessage(
&msg);
InBlock.gifDispatchMessage(
&msg);
ExpandedSubBlockEnd.gif}

ExpandedSubBlockEnd.gif}

InBlock.gifKillTimer(NULL,timerid);
InBlock.gifprintf(
"threadendhere/n");
InBlock.gif
return0;
ExpandedBlockEnd.gif}

None.gif
None.gif
int main()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gifDWORDdwThreadId;
InBlock.gifprintf(
"usetimerinworkthreadofconsoleapplication/n");
InBlock.gifHANDLEhThread
=CreateThread(NULL,0,Thread,0,0,&dwThreadId);
InBlock.gif_getch();
InBlock.gif
return0;
ExpandedBlockEnd.gif}

None.gif
None.gif
None.gif

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值