C/C++ 學習之 定時器,學習定時器
下面是兩個簡單的例子,說明在 windows 控制台應用程式中定時器的用法
1、直接聲明回呼函數,然後在回呼函數中處理訊息。
// programe for timer#include "stdio.h"#include "conio.h"#include <Windows.h>int count = 0;void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime){printf("WM_TIMER in work thread count = %d\n",count++);}int main(){SetTimer (NULL, 0, 1000, TimerProc);MSG msg; while(GetMessage(&msg,NULL,0,0)) {if(msg.message==WM_TIMER){DispatchMessage(&msg);if(count == 7){printf("should stop!\n");break;}} }KillTimer (NULL, 0);return 0;}
2、建立線程,線上程中建立訊息處理機制
//programe for timer
#include <windows.h> #include <stdio.h> #include <conio.h> unsigned long WINAPI Thread(PVOID pvoid); void main() { DWORD dwThreadId; printf("控制台應用程式:線程-定時器\n"); HANDLE hThread = CreateThread(NULL, 0, Thread, 0, 0, &dwThreadId);//安全等級,預設棧空間,線程名,線程參數,編程標誌,線程ID DWORD dwwait = WaitForSingleObject(hThread,1000*30); switch(dwwait) { case WAIT_ABANDONED: printf("main thread WaitForSingleObject return WAIT_ABANDONED\n"); break; case WAIT_OBJECT_0: printf("main thread WaitForSingleObject return WAIT_OBJECT_0\n"); break; case WAIT_TIMEOUT: printf("main thread WaitForSingleObject return WAIT_TIMEOUT\n"); break; } CloseHandle(hThread); getch(); } unsigned long WINAPI Thread(PVOID pvoid) { MSG msg; PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);//該函數為一個訊息檢查線程訊息佇列,並將該訊息(如果存在)放於指定的結構。//接收訊息的 MSG 結構指標,控制代碼,指定被檢查的訊息範圍裡的第一個訊息,最後一個,確定訊息如何被處理//PM_NOREMOVE,PeekMessage處理後,訊息不從隊列裡除掉//PM_REMOVE,PeekMessage處理後,訊息從隊列裡除掉//PM_NOYIELD,此標誌使系統不釋放等待調用程式閒置線程 UINT timerid = SetTimer(NULL,111,1000,NULL); BOOL bRet; int count = 0; while((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) { if(bRet == -1) { // handle the error and possibly exit } else if(msg.message == WM_TIMER) { printf("WM_TIMER in work thread count = %d\n",count++); if(count>4) break; } else { TranslateMessage(&msg); //將虛擬鍵訊息轉換為字元訊息,下一次線程調用函數GetMessage或PeekMessage時被讀出。 DispatchMessage(&msg); //該函數分發一個訊息給視窗程序,訊息傳遞給作業系統,然後作業系統去調用我們的回呼函數 } } KillTimer(NULL,timerid); printf("thread end here\n"); return 0; }