setTimer()只生成一次WM_TIMER消息

时间:2012-07-14 03:52:16

标签: visual-c++ mfc

我正在使用添加了资源ID且基于WM_TIMER消息的计时器。 我想在DrunkenDragon()上调用类似OnTimer()的例程,但在SetTimer(id,10sec,NULL)被调用后只调用一次。我们知道在KillTimer()例程内调用DrunkenDragon()会解决问题。可以接受这个,或者我错过了与计时器有关的东西。

3 个答案:

答案 0 :(得分:0)

int CYourDialog::OnInitDialog()
{
   __super::OnInitDialog();

   SetTimer(0x10, 10000, NULL);

   return true;
}

void CYourDialog::OnTimer(UINT_PTR ignore)
{
   DrunkenDragon();
}

确保您在留言地图中有ON_WM_TIMER

答案 1 :(得分:0)

您没有遗漏任何内容,您必须使用KillTimer系统停止生成WM_TIMER消息。

您还可以使用CreateTimerQueueTimer并以仅调用一次回调的方式设置参数。

See this for more details.

答案 2 :(得分:0)

(只有在遇到别人遇到此问题时才回答这个问题,并且对可用的答案不满意)

因此,在WindowClass.h中,您可以执行的是要使用的计时器标识符的枚举。虽然您当然可以使用原始数值,但从长远来看,使用符号可能更容易使用。

class WindowClass : CWnd
{
    // other parts of the interface...

protected:

    enum
    {
        TIMER_MAIN_UPDATE = 1,
        TIMER_PLASTERED_DRAGON
    };
};

同时,回到WindowClass.cpp,

int WindowClass::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    // { ... other initialization code }

    // In case you want to do other types of updates at regular intervals.
    SetTimer(TIMER_MAIN_UPDATE, 1000, NULL);

    // Note the symbolic identifiers.
    SetTimer(TIMER_PLASTERED_DRAGON, 10000, NULL);

    return 0;
}

但是,如果你想在创建窗口10秒后这样做,那将是唯一的好处。您也可以随时在其他事件处理程序中调用SetTimer():

void WindowClass::OnJustGotPaid()
{
    // { ... other handling }

    // Since our dragon is a real lightweight, it apparently only takes
    // 10 seconds to get him puking up flaming vomit.
    SetTimer(TIMER_PLASTERED_DRAGON, 10000, NULL);
}

当需要处理实际事件时,通常在Windows OnTimer()回调中处理。如果需要,可以通过在SetTimer()的第三个参数中指定有效的函数指针而不是NULL来将定时器事件定向到不同的(自定义)回调。

void WindowClass::OnTimer(UINT_PTR p_timer_id)
{
    switch(p_timer_id)
    {

    default:
        break;

    case TIMER_MAIN_UPDATE:

        // { ... main update code }
        break;

    case TIMER_PLASTERED_DRAGON:

        // Killing the timer first in case DrunkenDragon() takes a good
        // long while for whatever reason.
        KillTimer(TIMER_PLASTERED_DRAGON);

        DrunkenDragon();

        break;
    }
}
相关问题