Software & Finance

Visual C++ - Timer Sample MFC Dialog Based Application

Timers are very useful, if we want to monitor something based with constant interval. SetTimer is the function that can take 3 argument. The first argument is the identifier. The second argument is the interval in milliseconds. The third argument is the call back function and can be NULL, if you want to use the default function OnTimer(...). I have used default function for simplicity.


WM_TIMER is a message can be added through the dialog editor by RMB (Right Mosue Button) to properties on dialog.


The variabales can be added through wizard by RMB -> Add Variable...
It will popup the following dialog to add variables.



If you are an expert, then you do not need to go through wizard and directly make code changes. Wizrds are a quick start to get into the programming.


The following is the source code for Timer Sample Dialog Based Application. Scroll to the end of the page to see the download instructions on VS 2005 project and executables.


Source Code

BOOL CTimerSampleDlg::OnInitDialog()




      // Add "About..." menu item to system menu.


      // IDM_ABOUTBOX must be in the system command range.


      ASSERT(IDM_ABOUTBOX < 0xF000);


      CMenu* pSysMenu = GetSystemMenu(FALSE);

      if (pSysMenu != NULL)


            CString strAboutMenu;


            if (!strAboutMenu.IsEmpty())



                  pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);




      // Set the icon for this dialog.  The framework does this automatically

      //  when the application's main window is not a dialog

      SetIcon(m_hIcon, TRUE);             // Set big icon

      SetIcon(m_hIcon, FALSE);            // Set small icon


      m_listCtrl.InsertColumn( 0, _T("Time Index"));

      m_listCtrl.InsertColumn( 1, _T("Started At"));

      m_listCtrl.InsertColumn( 2, _T("Elapsed Milliseconds"));

      m_listCtrl.SetColumnWidth( 0, 100);

      m_listCtrl.SetColumnWidth( 1, 80);

      m_listCtrl.SetColumnWidth( 2, 155);


      return TRUE;  // return TRUE  unless you set the focus to a control



void CTimerSampleDlg::OnBnClickedOk()


    char buf[128];

    LV_ITEM lvitem;

      lvitem.iItem = m_TimerIdx;

      lvitem.mask = 0;

      lvitem.iSubItem = 0;

      m_listCtrl.InsertItem( &lvitem);

    sprintf(buf, _T("Timer : %d"), m_TimerIdx + 1);

    m_listCtrl.SetItemText( m_TimerIdx, 0, buf);


    CTime curr = CTime::GetCurrentTime();

      m_listCtrl.SetItemText( m_TimerIdx, 1, (const char*)curr.Format("%H:%M:%S"));

    m_listCtrl.SetItemText( m_TimerIdx, 2, "0");


    SetTimer(m_TimerIdx, 100, NULL);





void CTimerSampleDlg::OnTimer(UINT_PTR nIDEvent)


    int idx = nIDEvent;


    CString strTemp = m_listCtrl.GetItemText( idx, 2);


    strTemp.Format("%d", atoi(strTemp) + 100);


    m_listCtrl.SetItemText( idx, 2, strTemp);




Click here to download the complete project and executable