C++中Timer的用法
1. 使用windows api函數SetTimer設定計時器
UINT_PTR SetTimer( HWND hWnd, // 窗口句柄 UINT_PTR nIDEvent, // 定時器ID,多個定時器時,可以通過該ID判斷是哪個定時器 UINT uElapse, // 時間間隔,單位為毫秒 TIMERPROC lpTimerFunc // 回調函數 ); //如果已傳入參數nIDEvent,則函數的返回值與nIDEvent相同,如果參數nIDEvent為NULL,則函數的返回值為系統為這 //個定時器設定的一個ID
注意:設置第二個參數時要注意,如果設置的等待時間比處理時間短,程序可能會出現問題。
2. 編寫Timer的回調函數
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;
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!