一、程序運行界面如下:
二、程序思想與要點:
1)、本程序分兩種情況來獲取CPU的利用率,NT下利用ntdll.dll中沒有公開的API: NtQuerySystemInformation, 9x下利用注冊表來獲取CPU的利用率
code:NT
typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
PROCNTQSI NtQuerySystemInformation;
NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
GetModuleHandle("ntdll"),
"NtQuerySystemInformation"
);
if (!NtQuerySystemInformation)
{
return;
}
// get number of processors in the system
status = NtQuerySystemInformation(SystemBasicInformation,
&SysBaseInfo,sizeof(SysBaseInfo),NULL);
if (status != NO_ERROR)
{
return;
}
status = NtQuerySystemInformation(SystemTimeInformation,
&SysTimeInfo,sizeof(SysTimeInfo),0);
if (status!=NO_ERROR)
{
return;
}
// get new CPU''s idle time
status = NtQuerySystemInformation(SystemPerformanceInformation,
&SysPerfInfo,sizeof(SysPerfInfo),NULL);
if (status != NO_ERROR)
{
return;
}
// if it''s a first call - skip it
if (m_liOldIdleTime.QuadPart != 0)
{
// CurrentValue = NewValue - OldValue
dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(m_liOldIdleTime);
dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(m_liOldSystemTime);
// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime = dbIdleTime / dbSystemTime;
// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;
m_fNewUsges = (UINT)dbIdleTime;
}
9x略
2)、 通過 GlobalMemoryStatus來獲取內存的使用情況
code:
MEMORYSTATUS MemStat;
MemStat.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&MemStat);
m_ulNewUsges = MemStat.dwMemoryLoad;
3)、 程序中封裝了兩個類 CcpuUsgesCtl和CmemUsgesCtl,使用這兩這個類可以實現CPU,內存利用率的定時讀取,並以圖形化的形式顯示出來
三、使用
有兩種使用方法,不過要先把這個類的文件 add to project
1).聲明一個這兩類的對象,並用create來動態生成
such as:
CMemUsgesCtl m_ MyMemCtrl;
CCpuUsgesCtl m_ MyCpuCtrl;
…………
if(!m_MyCpuCtrl.Create(WS_CHILD | WS_VISIBLE, rect, this, IDC_CPUCTL))
{
TRACE0("Create m_MyCtrl Failed!");
return 0;
}
rect.left = rect.right + 20;
rect.right += lpCreateStruct->cx / 2;
if(!m_MyMemCtrl.Create(WS_CHILD | WS_VISIBLE,rect, this, IDC_MEMCTL))
{
TRACE0("Create m_MyCtrl Failed!");
return 0;
}
2)插入一個static控件,並從類向導中為其生成control形變量,最後將變量的類型換為我們就行了
四、結束語
控件利用內存來繪圖,實現了無閃爍顯示,歡迎指教!
本文配套源碼