CWnd::SetTimer
Installs a system timer.
UINT_PTR SetTimer( UINT_PTR nIDEvent, UINT nElapse, void (CALLBACK* lpfnTimer )(HWND, UINT, UINT_PTR, DWORD ) );
The timer identifier of the new timer if the function is successful. This value may or may not be equal to the value passed in through the nIDEvent parameter. An application should always pass the return value to the KillTimer member function to kill the timer. Nonzero if successful; otherwise, 0.
An interval value is specified, and every time the interval elapses, the system posts a WM_TIMER message to the installing message queue of the installing application or passes the message to an application-defined TimerProc callback function.
The lpfnTimer callback function need not be named TimerProc, but it must be declared as static and defined as follows.
void CALLBACK TimerProc( HWND hWnd, // handle of CWnd that called SetTimer UINT nMsg, // WM_TIMER UINT_PTR nIDEvent, // timer identification DWORD dwTime // system time );
This example uses CWnd::SetTimer, CWnd::OnTimer, and CWnd::KillTimer to handle WM_TIMER messages. The first timer is set up to send a WM_TIMER message to the main frame window every 2 seconds in OnStartTimer. The OnTimer event handler handles WM_TIMER messages for the main frame window. This method causes the PC speaker to beep every 2 seconds. The second timer sends a message to the callback function every 37.5 seconds. OnStopTimer will stop both timers by calling CWnd::KillTimer for each timer ID.
void CMainFrame::OnStartTimer() { // This timer uses a WM_TIMER message, not a callback. // Therefore, the timer is specific to this window. // m_nWindowTimer is a UINT_PTR field. m_nWindowTimer = SetTimer(1, 2000, NULL); // For this demo, we specify an interval that won't overlap // with the window timer. m_nCallbackTimer = SetTimer(2, 3750, &CMainFrame::MyTimerProc); // See whether we got the ID we requested in the first parameter. #ifdef _DEBUG CString str; str.Format(_T("m_ncallbackTImer ID = %d"), m_nCallbackTimer); TRACE(str); #endif } void CALLBACK CMainFrame::MyTimerProc( HWND hWnd, // handle of CWnd that called SetTimer UINT nMsg, // WM_TIMER UINT_PTR nIDEvent, // timer identification DWORD dwTime // system time ) { MessageBeep(0x00000030L); // Windows question sound. } void CMainFrame::OnStopTimer() { KillTimer(m_nWindowTimer); KillTimer(m_nCallbackTimer); } void CMainFrame::OnTimer(UINT nIDEvent) { MessageBeep(0xFFFFFFFF); // Beep // Call base class handler. CMDIFrameWnd::OnTimer(nIDEvent); }