明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺!

VC++設(shè)計圖形顯示CPU內(nèi)存使用率程序

[摘要][文章導(dǎo)讀] 本程序分兩種情況來獲取CPU的利用率,NT下利用ntdll.dll中沒有公開的API: NtQuerySystemInformation [正文]   下載本文源代碼http://www.yesky.com/imagesnew/software//0410/31/ccpum...
[文章導(dǎo)讀]

本程序分兩種情況來獲取CPU的利用率,NT下利用ntdll.dll中沒有公開的API: NtQuerySystemInformation

[正文]   


  下載本文源代碼
http://www.yesky.com/imagesnew/software//0410/31/ccpumemctl.rar 

  程序思想與要點:

  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;
}

  2)、 通過 GlobalMemoryStatus來獲取內(nèi)存的使用情況

  code:

MEMORYSTATUS MemStat;
MemStat.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&MemStat);
m_ulNewUsges = MemStat.dwMemoryLoad;

  3)、 程序中封裝了兩個類 CcpuUsgesCtl和CmemUsgesCtl,使用這兩這個類可以實現(xiàn)CPU,內(nèi)存利用率的定時讀取,并以圖形化的形式顯示出來

  使用

  有兩種使用方法,不過要先把這個類的文件 add to project

  1).聲明一個這兩類的對象,并用create來動態(tài)生成

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控件,并從類向?qū)е袨槠渖蒫ontrol形變量,最后將變量的類型換為我們就行了

  效果圖:



  結(jié)束語

  控件利用內(nèi)存來繪圖,實現(xiàn)了無閃爍顯示,歡迎指教!