定时器回调中的定时器 ID 与定义的定时器 ID 不同

Timer ID in timer call back is different from defined timer ID

我用 SetTimer 函数实现了两个定时器 :

UINT TimerId1 = SetTimer(NULL, IDT_TIMER1, 2000, TimerProc);
UINT TimerId2 = SetTimer(NULL, IDT_TIMER2, 2000, TimerProc);

并使用 GetMessage 循环泵送 windows 消息以获取计时器消息:

#define IDT_TIMER1  1
#define IDT_TIMER2  2

int main(int argc, char *argv[], char *envp[])
{
    MSG Msg;
    UINT TimerId1 = SetTimer(NULL, IDT_TIMER1, 2000, TimerProc);
    UINT TimerId2 = SetTimer(NULL, IDT_TIMER2, 2000, TimerProc);

    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    return 0;
}

由于要处理定时器消息,我为我的定时器实现了自定义函数 callback :

VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{
    if (nMsg == WM_TIMER)
    {
        switch (nIDEvent)
        {
        case IDT_TIMER1:
            cout << "Timer 1" << endl;
            break;
        case IDT_TIMER2:
            cout << "Timer 2" << endl;
            break;
        }
    }
}

问题出在我的 callback,我无法获得正确的计时器 ID,因为 none 个案例是 true。我的计时器 ID 定义为 12,但是 callback 中的计时器 ID 完全不同,它类似于 31270.

有什么建议吗?

线程计时器(当 hWnd 为 null 时),与 window 计时器相反,不使用您提供给它们的 ID - 而是它们分配自己的 ID,该 ID 由SetTimer 函数。

这在 SetTimer 的文档中有描述:

If the hWnd parameter is NULL, and the nIDEvent does not match an existing timer then it is ignored and a new timer ID is generated.

请注意,创建线程计时器后,您可以在以后调用 SetTimer 时使用该 ID 来修改它。

这是解决方案:

首先注意到SetTimer函数的第二个参数根据microsoft page(如指导):

nIDEvent

类型:UINT_PTR

非零计时器标识符。如果 hWnd 参数为 NULL,并且 nIDEvent 与现有计时器不匹配,则忽略它并生成新的计时器 ID。

因此,我的 hWnd 定时器都是 NULL,并且 12 没有匹配的定时器 ID。因此,SetTimer 返回的计时器 ID(根据应用程序决定需要 id),我必须使用它来处理我的 callback.

// Defined as public to use in callback
UINT TimerId1;
UINT TimerId2;

而我的 callback 定义如下:

VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime)
{
    if (nMsg == WM_TIMER)
    {
        if (nIDEvent == TimerId1)
        {
            cout << "Timer 1" << endl;
        }

        if (nIDEvent == TimerId2)
        {
            cout << "Timer 2" << endl;
        }
    }
}

输出为:

Timer 2
Timer 1
Timer 2
Timer 1
Timer 2
Timer 1
.
.
.