按键盘上方向键 ← 或 → 可快速上下翻页,按键盘上的 Enter 键可回到本书目录页,按键盘上方向键 ↑ 可回到本页顶部!
————未阅读完?加入书签已便下次继续阅读!
// 设置定时器
m_timer = SetTimer(1; 500; 0);
return TRUE; // return TRUE unless you set the focus to a control
}
利用 API 函数 SetTimer 启动定时器,函数原型如下:
UINT SetTimer( UINT nIDEvent; UINT nElapse; void (CALLBACK EXPORT* lpfnTimer)(HWND; UINT;
UINT; DWORD) );
o nIDEvent :非 0 定时器标志;
o nElapse :时间间隔;
o lpfnTimer :处理函数。
当起动定时器后,每间隔 nElapse 时间间隔,系统就会给应用程序发送 WM_TIMER 消
息,通常应用程序在 OnTimer 中响应这个消息。当程序退出时,需要调用 KillTimer 删除定
时器,释放系统资源,它的函数原型如下:
BOOL KillTimer( int nIDEvent );
o nIDEvent :调用 SetTimer 的返回值。
(2 )响应 OnTimer 消息
在初始化过程中,设置的时间间隔为 500 毫秒。即每隔 500 毫秒,测试一次 CPU 的使用
率。响应 OnTimer 消息,代码如下:
·168 ·
…………………………………………………………Page 178……………………………………………………………
第 7 章 图形图像
void CCpuUsageDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
int per;
// 得到当前 CPU 的使用率
per = m_Usage。GetCpuUsage();
// 计数
if(times 《 MAXTIMES)
times ++;
// 更新 CPU 使用记录数组
for(int i=0; iSelectObject(&newbrush);
pDC…》Rectangle(rect);
newbrush。DeleteObject();
pDC…》SelectObject(oldbrush);
// 绿色画笔; 绘制曲线
curpen。CreatePen(PS_SOLID; 2; RGB(0; 255; 0));
oldpen = pDC…》SelectObject(&curpen);
pDC…》MoveTo(rect。left; rect。bottom);
// 用线段近似曲线
for(int i=0; iLineTo(x; y);
}
// 恢复设备上下文
pDC…》SelectObject(oldpen);
curpen。DeleteObject();
}
(4 )动态绘制 CPU 使用记录
响应 CCpuUsageDlg 的 WM_PAINT 消息,用来动态绘制 CPU 使用记录,代码如下:
void CCpuUsageDlg::OnPaint()
·170 ·
…………………………………………………………Page 180……………………………………………………………
第 7 章 图形图像
{
if (IsIconic())
{
……
}
else
{
CPaintDC dc(this);
// 绘制 CPU 使用记录
DrawDiagram(&dc);
}
}
(5 )释放资源
最后,响应 CCpuUsageDlg 的 WM_DESTROY 消息,在程序退出时,删除定时器,释放
系统资源,代码如下:
void CCpuUsageDlg::OnDestroy()
{
CDialog::OnDestroy();
// 释放定时器资源
KillTimer(m_timer);
}
(6 )运行结果
程 序 运 行 后 , 界 面 如 图 7…2 至 7…5 所 示 。
·171 ·
…………………………………………………………Page 181……………………………………………………………
Visual C++ 6。0 程序设计从入门到精通
图 7…2 Cpu 使用记录 1