zoukankan      html  css  js  c++  java
  • 控制台中使用SetTimer的提醒

    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. void main()  
    6. {  
    7.     SetTimer(0, 0, 1000, &TimerProc);  
    8.     MSG   msg;     
    9.     while(GetMessage(&msg,NULL,0,0))     
    10.     {     
    11.         if(msg.message==WM_TIMER)     
    12.         {     
    13.             DispatchMessage(&msg);     
    14.         }     
    15.     }     
    16. }  

    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版本:

  • 相关阅读:
    好用,Office超效率速成技
    Oracle 12c从入门到精通:视频教学超值版
    用Excel学数据分析
    VMware、Citrix和Microsoft虚拟化技术详解与应用实践
    中文版Dreamweaver CC+Flash CC+Photoshop CC网页设计基础培训教程(新编实战型全功能培训教材)
    1467.二叉排序树
    1177.查找
    1178.复数集合
    1165.字符串匹配
    1166.迭代求立方根
  • 原文地址:https://www.cnblogs.com/findumars/p/3980121.html
Copyright © 2011-2022 走看看