地址:https://msdn.microsoft.com/zh-cn/library/49313fdf.aspx
UINT_PTR SetTimer( UINT_PTR nIDEvent, UINT nElapse, void (CALLBACK* lpfnTimer )(HWND, UINT, UINT_PTR, DWORD ) );
-
nIDEvent
-
指定一个非零计时器标识符。如果计时器标识符是唯一的,则此相同的值将由 SetTimer 返回。否则,SetTimer确定一个新的唯一值并返回它。针对窗口计时器(具备 NULL 回调功能),该值必须仅对与当前窗口相关的窗口计时器是唯一的。针对回调计时器,该值对于全部过程中的所有计时器必须是唯一的。因此,创建回调计时器时,很有可能返回的值不同于您指定的值。
nElapse
-
指定超时值或间隔(以毫秒为单位)。
lpfnTimer
-
指定应用程序提供的 TimerProc 处理 WM_TIMER 消息的回调函数的地址。如果此参数为 NULL,WM_TIMER消息将置于应用程序的消息队列中,并由 CWnd 对象处理。
如果函数运行成功,新计时器的计时器标识符。此值可能或可能不与通过 nIDEvent 参数传递的值相等。应用程序应始终将返回值传递给 KillTimer 成员函数以去除计时器。如果成功,则为 Nonzero;否则为 0。
指定了间隔值,并且每次间隔过后,系统都会将 WM_TIMER 消息发布到安装应用程序的安装消息队列,或者将此消息传递给由应用程序定义的 TimerProc 回调函数。
lpfnTimer 回调函数不需要命名为 TimerProc,但是,必须声明为静态的,定义如下。
void CALLBACK TimerProc( HWND hWnd, // handle of CWnd that called SetTimer UINT nMsg, // WM_TIMER UINT_PTR nIDEvent, // timer identification DWORD dwTime // system time );
此示例使用 CWnd::SetTimer、CWnd::OnTimer 和 CWnd::KillTimer 处理 WM_TIMER 消息。第一个计时器设置为按OnStartTimer 中时间每过 2 秒向主框架窗口发送一条 WM_TIMER 消息。 OnTimer 事件处理程序处理主框架窗口的WM_TIMER 消息。此方法可导致 PC 扬声器每 2 秒发出鸣声。第二个计时器每 3.75 秒发送消息给回调函数。OnStopTimer 将通过调用每个计时器 ID 的 CWnd::KillTimer 来停止两个计时器。
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); }
要求
标头: afxwin.h