C/C ++ learning timer, learning Timer
The following are two simple examples to describe how to use a timer in a windows console application.
1. directly declare the callback function and process the message in the callback function.
// 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. Establish a thread and establish a Message Processing Mechanism in the thread
//programe for timer
# Include <windows. h> # include <stdio. h> # include <conio. h> unsigned long WINAPI Thread (PVOID pvoid); void main () {DWORD dwThreadId; printf ("console application: Thread-timer \ n "); HANDLE hThread = CreateThread (NULL, 0, Thread, 0, 0, & dwThreadId); // security level, default stack space, Thread name, Thread parameter, programming flag, thread 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); // This function serves as a message queue of the Message check thread, and stores the message (if any) in the specified structure. // The MSG structure pointer and handle of the received message, which specifies the first message in the checked message range and the last one. determine how the message is processed // PM_NOREMOVE. After PeekMessage is processed, the message is not removed from the queue // PM_REMOVE. After PeekMessage is processed, the message is removed from the queue // PM_NOYIELD, this flag prevents the system from releasing the thread 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); // converts a virtual key message to a character message, which is read when the next thread calls the GetMessage or PeekMessage function. DispatchMessage (& msg); // This function distributes a message to the window program, transmits the message to the operating system, and then the operating system calls our callback function} KillTimer (NULL, timerid); printf ("thread end here \ n"); return 0 ;}