首页 > 解决方案 > 如何在 C++ 中创建定时器 无法计算出 CALLBACK 的定时器 ID 值

问题描述

现在使用TimerProc

VOID CALLBACK TimerProc(

    HWND hwnd,  // handle of window for timer messages 
    UINT uMsg,  // WM_TIMER message
    UINT idEvent,   // timer identifier
    DWORD dwTime    // current system time
   );

系统调用它来处理关联的 Timer 的 WM_TIMER 消息。让我们看一些代码。

#define IDT_TIMER1 1001
...

/* The Timer Procedure */
VOID CALLBACK TimerProc(HWND hwnd,   
                    UINT uMsg,  
                    UINT idEvent,   
                    DWORD dwTime)
   {
          MessageBox(NULL, "One second is passed, the timer procedure is called, killing the timer", "Timer Procedure", MB_OK);

          KillTimer(hwnd, idEvent);
   }

...

/* Creating the timer */
SetTimer(hwnd, IDT_TIMER1, 1000, (TIMERPROC)TimerProc);

...

我如何IDT_TIMER1获得TimerProc?idEvent 与此值不匹配,并且 uMsg 始终为 0x110 (WM_TIMER),它是否以某种方式编码,因为 idEvent 就像0x739Bwhile IDT_TIMER1is1001 (0x3E9)

标签: c++timer

解决方案


从文档中弄清楚。

idEvent - Specifies a nonzero timer identifier. If the `hWnd` parameter is NULL, this parameter is ignored.

所以它被忽略了。

像这样修复它

#define IDT_TIMER_1 1001
UINT_PTR Timer1IdEvent;

Timer1IdEvent = SetTimer(hwnd, IDT_TIMER1, 1000, (TIMERPROC)TimerProc);
...

VOID CALLBACK TimerProc(HWND hwnd,   
                    UINT uMsg,  
                    UINT idEvent,   
                    DWORD dwTime)
   {

          if( Timer1IdEvent == idEvent) {
              MessageBox(NULL, "One second is passed, the timer procedure is called, killing the timer", "Timer Procedure", MB_OK);

              KillTimer(hwnd, idEvent);
          }
   }

推荐阅读