C++ console with timer instance code

  • 2020-06-03 07:40:36
  • OfStack

This paper mainly studies the relevant instances of C++ console timer, which are as follows.

Use of Timer in the MFC program

There is a good timer function in MFC.

Use SetTimer() to set the timer Use KillTimer() to turn off the timer In the OnTimer() function, the response to the message WM_TIMER is the timer handler.

The source code

#define TIMER_UDP_QFX 3// The timer ID
int Period = 1000;//1000ms The timer 
// Set up the 1 A timer 
SetTimer(TIMER_UDP_QFX, Period, NULL);

// Set your own processing code in the timer handler function 
void CFlightMissionPage::OnTimer(UINT_PTR nIDEvent)
  //UPD  Update the interface 
  if (TIMER_UDP_QFX == nIDEvent)
  {// If the timer ID is  TIMER_UDP_QFX  , to be processed 
   // ·. · 
   // Handling code 
   // ·. · 
// Turn off the timer when you don't need it 

Use of Timer in console programs

This feature can help us do a lot of things without being too harsh on real-time metrics. So the question is, can this be used in general console applications? The answer, of course, is yes.

The function you want to use

UINT_PTR SetTimer( HWND hWnd,       // handle to window
 UINT_PTR nIDEvent,   // timer identifier
 UINT uElapse,      // time-out value
 TIMERPROC lpTimerFunc  // timer procedure

 HWND hwnd,     // handle to window
 UINT uMsg,     // WM_TIMER message
 UINT_PTR idEvent, // timer identifier
 DWORD dwTime    // current system time

The source code

#include <Windows.h>

// Console message response 
void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
  if(1 == idEvent)
  {// If it's a timer 1
    ::MessageBeep(0);//Beep call 


int main()

  int TimerID = 1;//Timer the ID is 1
  int peried = 1000;//Timer The interval is  1000ms

  // Set up the Timer  
  ::SetTimer(NULL, TimerID, peried, &TimerProc);

  ::MSG msg;
  while(::GetMessage(&msg, NULL, 0, 0))


This is the entire content of the C++ console timer instance code, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!

Related articles: