Wednesday, June 30, 2010

How to insert Timer in C++

Below is sample code that copied from my MRR Tool Project;

inside .h file

protected:
afx_msg UINT StartTimer (UINT TimerDuration); // Start the Timer
afx_msg BOOL StopTimer (UINT TimerVal); // Stop the Timer

inside .cpp file

UINT CMRR_ToolDlg::StartTimer (UINT TimerDuration)
{
UINT TimerVal;
TimerVal = SetTimer (IDT_TIMER, TimerDuration, NULL); // Starting the Timer
if (TimerVal == 0)
{
AfxMessageBox("Unable to obtain timer");
}
return TimerVal;
}


BOOL CMRR_ToolDlg::StopTimer (UINT TimerVal)
{
if (!KillTimer (TimerVal))
{
return FALSE;
}
// Place clean-up code following this point.
return TRUE;
}


Then Add WM_TIMER from 'Add windows Message Handler'
and add this code

void CMRR_ToolDlg::OnTimer(UINT nIDEvent)
{
switch ( timerEventWorkID )
{
case 1: // startWork()
StopTimer(Timeval);
connectServer();
break;
case 2: // startSendingData()
StopTimer(Timeval);
showStatus("Timeout Waiting Reply From BOS");
sendingMesraDataStatus = 2;
break;
default:
showStatus("Timer with wrong timerEventWorkID");
break;
}
CDialog::OnTimer(nIDEvent);
}


No comments: