本文简单介绍下VC中定时器设置。
首先,新建对话框应用程序,然后添加几个操作按钮。
定义相关变量
private: int m_nValue; DWORD m_dwTimeStarted; LARGE_INTEGER m_cupHZ; LARGE_INTEGER m_StartCount;
void CTimeCountDlg::OnTimer(UINT nIDEvent) { UpdateData(TRUE); switch(nIDEvent) { case 1: { m_nValue+=1000; m_sValue1.Format("%d",m_nValue); } break; case 2: { double dbTime = 0; dbTime = (::GetTickCount() - m_dwTimeStarted)*1.0; m_sValue2.Format("%f",dbTime); } break; case 3: { double dbTime = 0; MSG msg; UINT LFactor = 1000; while(::GetTickCount() - m_dwTimeStarted < 3*LFactor) { if (PeekMessage(&msg,0,0,0,PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } dbTime = (::GetTickCount() - m_dwTimeStarted)*1.0; m_sValue3.Format("%f",dbTime); } break; case 4: { UINT LFactor = 1000; double dbTimestamp = 0; LARGE_INTEGER CurCount; QueryPerformanceCounter(&CurCount); CurCount.QuadPart = CurCount.QuadPart - m_StartCount.QuadPart; dbTimestamp = double(CurCount.QuadPart)*LFactor; dbTimestamp = dbTimestamp/double(m_cupHZ.QuadPart); m_sValue4.Format("%f",dbTimestamp); } break; default: break; } UpdateData(FALSE); CDialog::OnTimer(nIDEvent); } void CTimeCountDlg::OnButton1() { m_nValue = 0; SetTimer(1,1000,NULL); KillTimer(2); KillTimer(3); KillTimer(4); } void CTimeCountDlg::OnButton2() { m_dwTimeStarted = ::GetTickCount(); SetTimer(2,1000,NULL); KillTimer(1); KillTimer(3); KillTimer(4); } void CTimeCountDlg::OnButton3() { m_dwTimeStarted = ::GetTickCount(); SetTimer(3,1000,NULL); KillTimer(1); KillTimer(2); KillTimer(4); } void CTimeCountDlg::OnButton4() { QueryPerformanceFrequency(&m_cupHZ); m_StartCount.QuadPart = 0; QueryPerformanceCounter(&m_StartCount); SetTimer(4,1000,NULL); KillTimer(1); KillTimer(2); KillTimer(3); }
运行效果
总结:
按钮一:直接使用定时器操作
按钮二:获取操作系统运行时间,然后相减,立即开始
按钮三:获取操作系统运行时间,然后相减,*s内运行或者*s后开始
按钮四:查询定时器计数值
原文地址:http://blog.csdn.net/bingdianlanxin/article/details/44903317