MFC - Timer



?>

A timer is a non-spatial object that uses recurring lapses of time from a computer or from your application. To work, every lapse of period, the control sends a message to the operating system. Unlike most other controls, the MFC timer has neither a button to represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method. This function call creates a timer for your application. Like the other controls, a timer uses an identifier.

Let us create a new MFC dialog based application.

Step 1 − Remove the Caption and set its ID to IDC_STATIC_TXT

Step 2 − Add the value variable for text control.

Timer

Step 3 − Go to the class view in solution.

Step 4 − Click the CMFCTimeDlg class.

Step 5 − In the Properties window, click the Messages button.

Timer

Step 6 − Click the WM_TIMER field and click the arrow of its combo box. Select OnTimer and implement the event.

void CMFCTimerDlg::OnTimer(UINT_PTR nIDEvent) { 
   // TODO: Add your message handler code here and/or call default 
   CTime CurrentTime = CTime::GetCurrentTime();  
	
   int iHours = CurrentTime.GetHour(); 
   int iMinutes = CurrentTime.GetMinute(); 
   int iSeconds = CurrentTime.GetSecond(); 
   CString strHours, strMinutes, strSeconds;  
 
   if (iHours < 10) 
      strHours.Format(_T("0%d"), iHours); 
   else 
      strHours.Format(_T("%d"), iHours);  
 
   if (iMinutes < 10) 
      strMinutes.Format(_T("0%d"), iMinutes); 
   else 
      strMinutes.Format(_T("%d"), iMinutes);  
   
   if (iSeconds < 10) 
      strSeconds.Format(_T("0%d"), iSeconds); 
   else 
      strSeconds.Format(_T("%d"), iSeconds);  
 
   m_strTimer.Format(_T("%s:%s:%s"), strHours, strMinutes, strSeconds); 
   
   UpdateData(FALSE); 
   CDialogEx::OnTimer(nIDEvent); 
}

Step 7 − When the above code is compiled and executed, you will see the following output.

Timer
mfc_windows_controls.htm
Advertisements