⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testcpuusagedlg.cpp

📁 实时检测cpu利用率
💻 CPP
字号:
// TestCpuUsageDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TestCpuUsage.h"
#include "TestCpuUsageDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
typedef struct
	{
		DWORD   dwUnknown1;
        ULONG   uKeMaximumIncrement;
        ULONG   uPageSize;
        ULONG   uMmNumberOfPhysicalPages;
        ULONG   uMmLowestPhysicalPage;
        ULONG   uMmHighestPhysicalPage;
        ULONG   uAllocationGranularity;
        PVOID   pLowestUserAddress;
        PVOID   pMmHighestUserAddress;
        ULONG   uKeActiveProcessors;
        BYTE    bKeNumberProcessors;
        BYTE    bUnknown2;
        WORD    wUnknown3;
	} SYSTEM_BASIC_INFORMATION;

    typedef struct
    {
	   LARGE_INTEGER   liIdleTime;
       DWORD           dwSpare[76];
    } SYSTEM_PERFORMANCE_INFORMATION;

    typedef struct
	{
		LARGE_INTEGER liKeBootTime;
        LARGE_INTEGER liKeSystemTime;
        LARGE_INTEGER liExpTimeZoneBias;
        ULONG         uCurrentTimeZoneId;
        DWORD         dwReserved;
	} SYSTEM_TIME_INFORMATION;


// ntdll!NtQuerySystemInformation (NT specific!)
//
// The function copies the system information of the
// specified type into a buffer
//
// NTSYSAPI
// NTSTATUS
// NTAPI
// NtQuerySystemInformation(
//    IN UINT SystemInformationClass,    // information type
//    OUT PVOID SystemInformation,       // pointer to buffer
//    IN ULONG SystemInformationLength,  // buffer size in bytes
//    OUT PULONG ReturnLength OPTIONAL   // pointer to a 32-bit
//                                       // variable that receives
//                                       // the number of bytes
//                                       // written to the buffer 
// );
typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);

PROCNTQSI NtQuerySystemInformation;
BOOL CHECKCPU = FALSE;
long m_lCpuStartTickCount;
long m_lCpuPassedTickCount;

UINT _CheckCpu( LPVOID lpvoid )
{
	CTestCpuUsageDlg *pthis = ( CTestCpuUsageDlg *)lpvoid;

	SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
    SYSTEM_TIME_INFORMATION        SysTimeInfo;
    SYSTEM_BASIC_INFORMATION       SysBaseInfo;
    double                         dbIdleTime;
    double                         dbSystemTime;
    LONG                           status;
    LARGE_INTEGER                  liOldIdleTime = { 0,0 };
    LARGE_INTEGER                  liOldSystemTime = { 0,0 };

    NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
                                          GetModuleHandle("ntdll"),
                                         "NtQuerySystemInformation"
                                         );

    if (!NtQuerySystemInformation)
        return S_FALSE;

    // get number of processors in the system
    status = NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
    if (status != NO_ERROR)
        return S_FALSE;
    
		
    while(status == NO_ERROR )
    {
	
		if( !CHECKCPU )
			break;
        // get new system time
	    status = NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
        if ( status != NO_ERROR )
            return S_FALSE;

        // get new CPU's idle time
        status = NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
        if (status != NO_ERROR)
            return S_FALSE;

        // if it's a first call - skip it
       if (liOldIdleTime.QuadPart != 0)
       {
		            // CurrentValue = NewValue - OldValue
            dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
            dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);

            // CurrentCpuIdle = IdleTime / SystemTime
            dbIdleTime = dbIdleTime / dbSystemTime;

            // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
            dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SysBaseInfo.bKeNumberProcessors + 0.5;

           
       }
	   
        long m_lCurrentCpuTickCount = GetTickCount( );
		TRACE(" m_lCurrentCpuTickCount = %ld",m_lCurrentCpuTickCount);
		m_lCpuPassedTickCount = m_lCurrentCpuTickCount - m_lCpuStartTickCount;
        TRACE(" m_lCpuPassedTickCount = %ld",m_lCpuPassedTickCount);

        // store new CPU's idle and system time
        liOldIdleTime = SysPerfInfo.liIdleTime;
        liOldSystemTime = SysTimeInfo.liKeSystemTime;
		TRACE("\nCpuUsage is %3d%%\n",UINT(dbIdleTime));
				
		pthis->PostMessage( WM_DATA,NULL,int( dbIdleTime ) );
		Sleep(1000);
		
	}
    
	return 0;
}
	

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestCpuUsageDlg dialog

CTestCpuUsageDlg::CTestCpuUsageDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTestCpuUsageDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTestCpuUsageDlg)
	m_strCpuUsage = _T("");
	m_SystemType = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTestCpuUsageDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTestCpuUsageDlg)
	DDX_Control(pDX, IDC_SYSTEMTYPE, m_systemType);
	DDX_Control(pDX, IDC_XGRIDCTRLCTRL1, m_grid);
	DDX_Text(pDX, IDC_CPUUSAGE, m_strCpuUsage);
	DDX_Text(pDX, IDC_SYSTEMTYPE, m_SystemType);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTestCpuUsageDlg, CDialog)
	//{{AFX_MSG_MAP(CTestCpuUsageDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_PRINT, OnPrint)
	ON_MESSAGE(WM_DATA,OnData)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTestCpuUsageDlg message handlers

BOOL CTestCpuUsageDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTestCpuUsageDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTestCpuUsageDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTestCpuUsageDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CTestCpuUsageDlg::OnTimer(UINT nIDEvent) 
{
	
	m_grid.SetCurveDataOne(atol(m_strCpuUsage ));
	

	
	
	CDialog::OnTimer(nIDEvent);
}

void CTestCpuUsageDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CDialog::OnCancel();
}

void CTestCpuUsageDlg::OnOK() 
{
	CButton* pButton = ( CButton * )GetDlgItem( IDOK );
	pButton->EnableWindow( FALSE );
	TestOSVersion( );
	m_systemType.SetWindowText( m_SystemType );

	// 获取当前CPU利用率,在线程_CheckCpu中实现

	CHECKCPU = TRUE;
	AfxBeginThread( _CheckCpu,this );

    m_lCpuStartTickCount = GetTickCount( );
	TRACE("m_lCpuStartTickCount = %ld ", m_lCpuStartTickCount);
	//画折线图
/*	m_grid.SetGHText("CPU利用率实时采集图");
	m_grid.SetGHTextColor(RGB(250,30,30));
	m_grid.SetNumColor(RGB(20,0,255));*/
	long length = m_grid.GetDataWidth();
	long *data;
	data = new long[length];
	for(int i = 0;i<length;i++)
	{
		data[i] = m_grid.SetCurveDataOne( atol( m_strCpuUsage ) );
	}
	m_grid.SetCurveDataA(data,length);
	m_time = SetTimer(1,100,NULL);

	//CDialog::OnOK();
}

void CTestCpuUsageDlg::OnPrint() 
{
	// TODO: Add your control notification handler code here
	
}

CString CTestCpuUsageDlg::TestOSVersion()
{
	typedef enum tagWin32SysType
	{
		Windows32s,
	    WindowsNT3,
	    Windows95,
	    Windows98,
	    WindowsME,
	    WindowsNT4,
	    Windows2000,
	    WindowsXP
	}Win32SysType;
//判断操作系统涵数及变量
	Win32SysType  ShellType;
	DWORD winVer;
	OSVERSIONINFO *osvi;


	winVer = GetVersion( );
	if( winVer < 0x80000000 )
	{/*NT */
		ShellType = WindowsNT3;
		m_SystemType = "WindowsNT3";
		osvi = ( OSVERSIONINFO *)malloc( sizeof( OSVERSIONINFO ) );
		if ( osvi != NULL )
		{
			memset( osvi,0,sizeof( OSVERSIONINFO ) );
			//osvi-&gt;
			osvi->dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
			GetVersionEx( osvi );
			if( osvi->dwMajorVersion == 4L )
			{
				ShellType=WindowsNT4;
				m_SystemType = "WindowsNT4";
			}
			else
				if( osvi->dwMajorVersion == 5L && osvi->dwMinorVersion == 0L)
				   {
					   ShellType = Windows2000;
					   m_SystemType = "Windows2000";
				}
			    else
					if( osvi->dwMajorVersion == 5L && osvi->dwMinorVersion == 1L )
					{
					    ShellType = WindowsXP;
						m_SystemType = "WindowsXP";
					}
			free( osvi );
		}
	}
	else if  ( LOBYTE( LOWORD( winVer ) ) < 4)
	{
		ShellType = Windows32s;
		m_SystemType = "Windows32s";
	}
	else
	{
		ShellType = Windows95;
		osvi = (OSVERSIONINFO *)malloc( sizeof( OSVERSIONINFO ) );
		if ( osvi != NULL )
		{
			memset( osvi,0,sizeof( OSVERSIONINFO ) );
			
			osvi->dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
			GetVersionEx( osvi );
			if( osvi->dwMajorVersion == 4L && osvi->dwMinorVersion == 10L)
			{
				 ShellType = Windows98;
			     m_SystemType = "Windows98";
			}
			else
				if( osvi->dwMajorVersion == 4L && osvi->dwMinorVersion == 90L )
				{
					ShellType = WindowsME;
					m_SystemType = "WindowsME";
				}
			free( osvi );
		}
	}


	
	TRACE("OS is %s",m_SystemType );
	return m_SystemType;



}



LRESULT CTestCpuUsageDlg::OnData(WPARAM wparam,LPARAM lparam)
{
	m_strCpuUsage.Format("     %3d%%\n",int(lparam));
	UpdateData(FALSE);
	return 1;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -