C++中Timer的用法

1. 使用windows api函數SetTimer設定計時器ios

UINT_PTR SetTimer( 
HWND hWnd,   //   窗口句柄 
UINT_PTR nIDEvent,   //   定時器ID,多個定時器時,能夠經過該ID判斷是哪一個定時器 
UINT uElapse,   //   時間間隔,單位爲毫秒 
TIMERPROC lpTimerFunc   //   回調函數 
); 
 //若是已傳入參數nIDEvent,則函數的返回值與nIDEvent相同,若是參數nIDEvent爲NULL,則函數的返回值爲系統爲這
//個定時器設定的一個ID

注意:設置第二個參數時要注意,若是設置的等待時間比處理時間短,程序可能會出現問題。windows

2. 編寫Timer的回調函數api

void CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nTimerid, DWORD dwTime);
//hWnd: 與SetTimer中所傳入的hWnd一致
//nMsg: WM_TIMER消息
//nTimerid: 計時器編號
//dwTime: 從系統啓動到如今的時間(用毫秒錶示),這是由GetTickCount函數所返回的

3. 在使用完計時器後必須調用「KillTimer(NULL, iTimerID)」來銷燬計時器函數

Sample code
#include <iostream>
#include <windows.h>

void CALLBACK TimerProc(HWND hwnd, UINT Msg, UINT idEvent, DWORD dwTime);

int main()
{
 UINT timerId = 1;
 MSG msg;
 
// int n = GetMessage(&msg, NULL, NULL, NULL);  //Wait for message, block the thread when getting no message

 SetTimer(NULL, timerId, 1000, TimerProc);  //每間隔1000毫秒定時器發送 一條信息,並執行回調函數中的代碼
 int nTemp;
 while ((nTemp = GetMessage(&msg, NULL, NULL, NULL)) && (-1 != nTemp) && (0 != nTemp))
 {
  if (WM_TIMER == msg.message)
  {
   cout << "I got a message" << endl;
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
 }
 return 0;
}
void CALLBACK TimerProc(HWND hwnd, UINT Msg, UINT idEvent, DWORD dwTime)
{
 cout << "HelloWorld" << endl;
}
相關文章
相關標籤/搜索