1. Setting a timer using the Windows API function SetTimer
Uint_ptr SetTimer (HWND hwnd,//Window handle uint_ptr nidevent,//timer ID, multiple timers, which can be determined by this ID is which timer UINT uelapse,//time interval , the unit is millisecond Timerproc lptimerfunc//callback function); If the parameter nidevent is passed in, the return value of the function is the same as nidevent, and if the parameter nidevent is NULL, the return value of the function is an ID set by the system for this//timer
Note: When setting the second parameter, it is important to note that if you set the wait time to be shorter than the processing time, the program may be having problems.
2. Writing a timer callback function
void CALLBACK Timerproc (HWND hwnd, UINT nmsg, uint Ntimerid, DWORD dwtime);//hwnd: Consistent with SetTimer incoming HWND//nmsg:wm_timer message Ntimerid: Timer number//dwtime: The time from System boot to present (in milliseconds), which is returned by the GetTickCount function
3. You must call "KillTimer (NULL, Itimerid)" to destroy the timer after you have finished using the timer
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,&NBSP;TIMERID,&NBSP;1000,&NBSP;TIMERPROC); //each interval of 1000 milliseconds the timer sends a message, and executes the code in the callback function 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" &NBSP;<<&NBSP;ENDL;}
Usage of timer in C + +