Usage of timer in C + +

Source: Internet
Author: User

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 (&AMP;MSG);    dispatchmessage (&msg);   } } return 0;} Void callback timerproc (hwnd hwnd, uint msg, uint idevent, dword  Dwtime) { cout <<  "HelloWorld" &NBSP;&LT;&LT;&NBSP;ENDL;}

Usage of timer in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.