码迷,mamicode.com
首页 > 其他好文 > 详细

控制台中使用SetTimer的提醒

时间:2014-09-18 22:09:14      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   ar   strong   div   

SetTimer是设置定时器,每隔一段时间执行一个操作,原型如下

 

  UINT_PTR SetTimer(

  HWND hWnd, // 窗口句柄

  UINT_PTR nIDEvent, // 定时器ID,多个定时器时,可以通过该ID判断是哪个定时器

  UINT uElapse, // 时间间隔,单位为毫秒

  TIMERPROC lpTimerFunc // 回调函数

 

  );

 

它是通过分发WM_TIMER消息来触发回调函数的,看下面代码

 

[cpp] view plaincopy
 
  1. void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime)  
  2. {  
  3.   printf("%s","abc");  
  4.      
  5. }  
  6. void main()  
  7. {  
  8.     SetTimer(0, 0, 1000, &TimerProc);  
  9. }  

 

 

你认为上面的代码会正确执行吗,答案是不会,回调函数根本得不到执行。因为虽然使用了SetTimer,但是没有对WM_TIMER消息进行分发,所以不会触发回调函数,我们修改如下

 

[cpp] view plaincopy
 
  1. void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime)  
  2. {  
  3.   printf("%s","abc");  
  4.      
  5. }  
  6. void main()  
  7. {  
  8.     SetTimer(0, 0, 1000, &TimerProc);  
  9.     MSG   msg;     
  10.     while(GetMessage(&msg,NULL,0,0))     
  11.     {     
  12.         if(msg.message==WM_TIMER)     
  13.         {     
  14.             DispatchMessage(&msg);     
  15.         }     
  16.     }     
  17. }  

 

OK,看到上面的while循环了吗,这里就是获取每秒钟发出的WM_TIMER消息,并分发下去,通知回调函数开始执行。

参考:http://blog.csdn.net/bdmh/article/details/6371443

经测试可行,完整代码:

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"

void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime)
{
  printf("%s","abc");
   
}
void main()
{
    SetTimer(0, 0, 1000, &TimerProc);
    MSG   msg;   
    while(GetMessage(&msg,NULL,0,0))   
    {   
        if(msg.message==WM_TIMER)   
        {   
            DispatchMessage(&msg);   
        }   
    }   
}

如果这样写:

MSG msg;
GetMessage(&msg, NULL, 0, 0);

这样消息队列是有了,但是没有人分发消息那还是不行,不会执行TimerProc的内容的。

----------------------------------------------------------------------------------------------

Delphi版本:

控制台中使用SetTimer的提醒

标签:style   blog   http   color   io   使用   ar   strong   div   

原文地址:http://www.cnblogs.com/findumars/p/3980121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!