一、SetTimer表示的是定義個定時器。根據(jù)定義指定的窗口,在指定的窗口(CWnd)中實現(xiàn)OnTimer事件,這樣,就可以相應(yīng)事件了。
SetTimer有兩個函數(shù)。
①一個是全局的函數(shù)::SetTimer()
UINT SetTimer(
HWND hWnd, // handle of window for timer messages
UINT nIDEvent, // timer identifier
UINT uElapse, // time-out value
TIMERPROC lpTimerFunc // address of timer procedure
);
其中hWnd 是指向CWnd的指針,即處理Timer事件的窗口類。因此繼承CWnd的子類均可以定義SetTimer事件。
②SetTimer() 在CWnd中也有定義,即SetTimer()是CWnd的一個成員函數(shù)。CWnd的子類可以調(diào)用該函數(shù),來設(shè)置觸發(fā)器。
UINT SetTimer(UINT nIDEvent, UINT nElapse, void (CALLBACK EXPORT* lpfnTimer)(HWND, UINT, UINT, DWORD) );
參數(shù)含義:
nIDEvent:是指設(shè)置這個定時器的iD,即身份標(biāo)志,這樣在OnTimer()事件中,才能根據(jù)不同的定時器,來做不同的事件響應(yīng)。這個ID是一個無符號的整型。
nElapse
是指時間延遲。單位是毫秒。這意味著,每隔nElapse毫秒系統(tǒng)調(diào)用一次Ontimer()。
void (CALLBACK EXPORT* lpfnTimer)(HWND, UINT, UINT, DWORD)
Specifies the address of the application-supplied TimerProc callback function that processes the WM_TIMER messages. If this parameter is NULL, the WM_TIMER messages are placed in the application’s message queue and handled by the CWnd object。
意思是,指定應(yīng)用程序提供的TimerProc回調(diào)函數(shù)的地址,來處里這個Timer事件。如果是NULL,系統(tǒng)將交由OnTimer()來處理這個Timer事件。
所以,一般情況下,我們將這個值設(shè)為NULL,有設(shè)置該定時器的對象中的OnTimer()函數(shù)來處理這個事件。
例:SetTimer(1,1000,NULL);
如果我要加入兩個或者兩個以上的 timer怎么辦? 繼續(xù)用SetTimer函數(shù)吧,上次的timer的ID是1,這次可以是2,3,4。
SetTimer(2,1000,NULL);
SetTimer(3,500,NULL);
WINDOWS會協(xié)調(diào)他們的。當(dāng)然onTimer函數(shù)體也要發(fā)生變化,要在函數(shù)體內(nèi)添加每一個timer的處理代碼:
onTimer(nIDEvent)
{
switch(nIDEvent)
{
case 1:........;
break;
case 2:.......;
break;
case 3:......;
break;
}
}
二、我們再看看KillTimer()和OnTimer()的定義:
KillTimer同SetTimer()一樣,他也有兩個,一個是全局的::KillTimer(),另一個是CWnd的一個函數(shù)。他的聲明如下:
//全局函數(shù)
BOOL KillTimer(
HWND hWnd, // handle of window that installed timer
UINT uIDEvent // timer identifier
);
//CWnd函數(shù)
BOOL KillTimer(int nIDEvent );
這兩個函數(shù)表示的意思是將iD為nIDEVENT的定時器移走。使其不再作用。其用法如同SetTimer()一樣。
再看看OnTimer()
CWnd::OnTimer
afx_msg void OnTimer(UINT nIDEvent);
ontimer() 是響應(yīng)CWnd對象產(chǎn)生的WM_Timer消息。nIDEvent表示要響應(yīng)TIMER事件的ID。
例子:SetTimer(2,2000,NULL);
OnTimer(UINT nIDEvent);//此時SetTimer中的2將傳遞給nIDEvent