2012-07-14 58 views
0

我正在使用添加了資源ID並基於WM_TIMER消息的定時器。 我想在OnTimer()上調用像DrunkenDragon()這樣的程序,但在調用SetTimer(id,10sec,NULL)後只有一次。我們知道在DrunkenDragon()例程內調用KillTimer()將解決此問題。是否可以這樣做,還是我錯過了一些很棒的定時器。setTimer()僅生成WM_TIMER消息一次

+0

爲什麼使用資源ID?您可以使用計數器變量來檢查是否第一次啓動定時器。 – Ajay 2012-07-14 04:56:34

回答

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

    SetTimer(0x10, 10000, NULL); 

    return true; 
} 

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

並確保您在消息映射中有ON_WM_TIMER

0

你不會錯過任何東西,你將不得不使用KillTimer系統停止生成WM_TIMER消息。

您也可以使用CreateTimerQueueTimer並設置參數,只調用一次回調的方式。

See this for more details.

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; 
    } 
}