1.获取CPU信息,使用System.Diagnostics.PerformanceCounter获取CPU信息,System.Environment.ProcessorCount获取CPU核数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
    public class cpu
    {
        private static readonly cpu instance = new cpu();
        private static System.Diagnostics.PerformanceCounter pcCpuLoad;
        private static System.Diagnostics.PerformanceCounter[] counters;
        public cpu()
        {
            //CPU个数
            m_ProcessorCount = Environment.ProcessorCount;
            //初始化CPU计数器
            pcCpuLoad = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");

            counters = new System.Diagnostics.PerformanceCounter[System.Environment.ProcessorCount];

            for (int i = 0; i < counters.Length; i++)
            {
                counters[i] = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString());
            }
            //System.Threading.Thread.Sleep(1000);
        }
        /// <summary>
        /// 获取整体CPU使用情况
        /// </summary>
        /// <returns></returns>
        public float getTotalMonitor()
        {

            //GC=  new System.Diagnostics.PerformanceCounter(".NET CLR Memory", "% Time in GC", "_Total");
            //pcCpuLoad.MachineName = ".";
            return pcCpuLoad.NextValue();
            //return instance;
        }
        /// <summary>
        /// 获取各个核CPU使用情况
        /// </summary>
        /// <returns></returns>
        public float[] getValue()
        {
            List<float> listResult = new List<float>();

            for (int i = 0; i < counters.Length; i++)
            {
                //counters[i] = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString());
                float f = counters[i].NextValue();
                listResult.Add(f);
            }
            return listResult.ToArray();


        }

        private static int m_ProcessorCount = 0;   //CPU个数    
        /// <summary>
        /// 获取核数
        /// </summary>
        /// <returns></returns>
        public int getProcessorCount()
        {
            return cpu.m_ProcessorCount;
        }
    }
}

2.获取内存信息。

  a) 使用WMI的Win32_PhysicalMemory获取内存信息。

  b) WINDOWSAPI的GlobalMemoryStatus方法.

  c) 引用 Microsoft.VisualBasic.dll类库,使用ComputerInfo类型的AvailablePhysicalMemory和TotalPhysicalMemory来获取当前剩余/全部物理内存

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
   public  class neicun
    {

       [DllImport("kernel32")]
       public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);

       [DllImport("kernel32")]
       public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
       [DllImport("kernel32")]
       public static extern void GetSystemInfo(ref  CPU_INFO cpuinfo);
       [DllImport("kernel32")]
       public static extern void GlobalMemoryStatus(ref  MEMORY_INFO meminfo);
       [DllImport("kernel32")]
       public static extern void GetSystemTime(ref  SYSTEMTIME_INFO stinfo);
       // [DllImport("kernel32")]
       //public static extern bool GlobalMemoryStatusEx(ref MEMORYEX_INFO memexinfo);


       [return: MarshalAs(UnmanagedType.Bool)]

       [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]

       public static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
        
  
   }
   //定义以下各结构  
   //定义CPU的信息结构  
   [StructLayout(LayoutKind.Sequential)]
   public struct CPU_INFO
   {
       public uint dwOemId;
       public uint dwPageSize;
       public uint lpMinimumApplicationAddress;
       public uint lpMaximumApplicationAddress;
       public uint dwActiveProcessorMask;
       public uint dwNumberOfProcessors;
       public uint dwProcessorType;
       public uint dwAllocationGranularity;
       public uint dwProcessorLevel;
       public uint dwProcessorRevision;
   }
   //定义内存的信息结构  
   [StructLayout(LayoutKind.Sequential)]
   public struct MEMORY_INFO
   {
       public uint dwLength;
       public uint dwMemoryLoad;
       public uint dwTotalPhys;
       public uint dwAvailPhys;
       public uint dwTotalPageFile;
       public uint dwAvailPageFile;
       public uint dwTotalVirtual;
       public uint dwAvailVirtual;
   }
   [StructLayout(LayoutKind.Sequential)]
   public struct MEMORYEX_INFO
   {
       public uint dwLength;
       public uint dwMemoryLoad;
       public long ullTotalPhys;
       public long ullAvailPhys;
       public long ullTotalPageFile;
       public long ullAvailPageFile;
       public long ullTotalVirtual;
       public long ullAvailVirtual;
       public long ullAvailExtendedVirtual;
   }

   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

   public class MEMORYSTATUSEX
   {
       /// <summary>
       /// MEMORYSTATUS结构的大小,在调GlobalMemoryStatus函数前用sizeof()函数求得,用来供函数检测结构的版本。
       /// 本结构的长度
       /// </summary>
       public uint dwLength;
       /// <summary>
       /// 返回一个介于0~100之间的值,用来指示当前系统内存的使用率。
       /// 已用内存的百分比
       /// </summary>
       public uint dwMemoryLoad;
       /// <summary>
       /// 返回总的物理内存大小,以字节(byte)为单位。
       /// 物理内存总量
       /// </summary>
       public ulong ullTotalPhys;
       /// <summary>
       /// 返回可用的物理内存大小,以字节(byte)为单位。
       /// 可用物理内存
       /// </summary>
       public ulong ullAvailPhys;
       /// <summary>
       /// 显示可以存在页面文件中的字节数。注意这个数值并不表示在页面文件在磁盘上的真实物理大小。
       /// 交换文件总的大小
       /// </summary>
       public ulong ullTotalPageFile;
       /// <summary>
       /// 返回可用的页面文件大小,以字节(byte)为单位。
       /// 交换文件中空闲部分大小
       /// </summary>
       public ulong ullAvailPageFile;
       /// <summary>
       /// 返回调用进程的用户模式部分的全部可用虚拟地址空间,以字节(byte)为单位。
       /// 用户可用的地址空间
       /// </summary>
       public ulong ullTotalVirtual;
       /// <summary>
       /// 返回调用进程的用户模式部分的实际自由可用的虚拟地址空间,以字节(byte)为单位。
       /// 当前空闲的地址空间
       /// </summary>
       public ulong ullAvailVirtual;
       /// <summary>
       /// 返回调用进程的用户模式部分的实际自由可用扩展的虚拟地址空间,以字节(byte)为单位。
       /// 当前空闲的地址扩展空间
       /// </summary>
       public ulong ullAvailExtendedVirtual;

       public MEMORYSTATUSEX()
       {

           this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));

       }

   }

   //定义系统时间的信息结构  
   [StructLayout(LayoutKind.Sequential)]
   public struct SYSTEMTIME_INFO
   {
       public ushort wYear;
       public ushort wMonth;
       public ushort wDayOfWeek;
       public ushort wDay;
       public ushort wHour;
       public ushort wMinute;
       public ushort wSecond;
       public ushort wMilliseconds;
   }
  
}

 3.调用方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Practice
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //调用GetWindowsDirectory和GetSystemDirectory函数分别取得Windows路径和系统路径  
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            neicun.GetWindowsDirectory(Buff, nChars);
            string a = "Windows路径:" + Buff.ToString();
            neicun.GetSystemDirectory(Buff, nChars);
            string a1 = "系统路径:" + Buff.ToString();
            //调用GetSystemInfo函数获取CPU的相关信息  
            CPU_INFO CpuInfo;
            CpuInfo = new CPU_INFO();
            neicun.GetSystemInfo(ref  CpuInfo);
            string a2 = "本计算机中有" + CpuInfo.dwNumberOfProcessors.ToString() + "个CPU";
            string a3 = "CPU的类型为" + CpuInfo.dwProcessorType.ToString();
            string a4 = "CPU等级为" + CpuInfo.dwProcessorLevel.ToString();
            string a5= "CPU的OEM  ID为" + CpuInfo.dwOemId.ToString();
            string a6 = "CPU中的页面大小为" + CpuInfo.dwPageSize.ToString();
            //调用GlobalMemoryStatus函数获取内存的相关信息  
            MEMORY_INFO MemInfo;
            MemInfo = new MEMORY_INFO();
            neicun.GlobalMemoryStatus(ref  MemInfo);
            string a7 = MemInfo.dwMemoryLoad.ToString() + "%的内存正在使用";
            string a8= "物理内存共有" + MemInfo.dwTotalPhys.ToString() + "字节";
            string a9= "可使用的物理内存有" + MemInfo.dwAvailPhys.ToString() + "字节";
            string a10= "交换文件总大小为" + MemInfo.dwTotalPageFile.ToString() + "字节";
            string a11 = "尚可交换文件大小为" + MemInfo.dwAvailPageFile.ToString() + "字节";
            string a12 = "总虚拟内存有" + MemInfo.dwTotalVirtual.ToString() + "字节";
            string a13 = "未用虚拟内存有" + MemInfo.dwAvailVirtual.ToString() + "字节";
            decimal a16 = ConvertBytes(MemInfo.dwTotalPhys.ToString(), 1);
            decimal a17 = ConvertBytes(MemInfo.dwTotalPhys.ToString(), 2);
            decimal a18 = ConvertBytes(MemInfo.dwTotalPhys.ToString(), 3);
            //调用GetSystemTime函数获取系统时间信息  
            SYSTEMTIME_INFO StInfo;
            StInfo = new SYSTEMTIME_INFO();
            neicun.GetSystemTime(ref  StInfo);
            string a14 = StInfo.wYear.ToString() + "年" + StInfo.wMonth.ToString() + "月" + StInfo.wDay.ToString() + "日";
            string a15 = (StInfo.wHour + 8).ToString() + "点" + StInfo.wMinute.ToString() + "分" + StInfo.wSecond.ToString() + "秒";

            MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
            bool b = neicun.GlobalMemoryStatusEx(ms);
            string a82 = ms.ullAvailPageFile.ToString();

            cpu c = new cpu();
            while(true)
            {
                int t = c.getProcessorCount();
                float q = c.getTotalMonitor();
                float[] l = c.getValue();

                System.Threading.Thread.Sleep(1000);
            }
        }

      
            public static decimal ConvertBytes(string b, int iteration)
            {
                long iter = 1;
                for (int i = 0; i < iteration; i++)
                    iter *= 1024;
                return Math.Round((Convert.ToDecimal(b)) / Convert.ToDecimal(iter), 2, MidpointRounding.AwayFromZero);
            }
        
    }
}

4.实时折线图

使用微软自带Chart控件编写自定义控件

    public partial class twaveformchart : UserControl
    {
        /// <summary>
        /// 队列长度
        /// </summary>
        private int queueCount = 60;
        /// <summary>
        /// 数据队列
        /// </summary>
        private Queue<double> dataQueue = null;
        /// <summary>
        /// 
        /// </summary>
        private System.Windows.Forms.Timer timer1 = null;
        /// <summary>
        /// 
        /// </summary>        
        //private int num = 5;

        private bool isFirst = false;
        public twaveformchart()
        {
            InitializeComponent();
        }

        private void twaveformchart_Load(object sender, EventArgs e)
        {
            dataQueue = new Queue<double>(queueCount);

            InitChart();
            timer1 = new System.Windows.Forms.Timer();
            timer1.Interval = _refreshRate * 1000;
            timer1.Tick += delegate(object o, EventArgs args)
            {
                DoWork();
            };

            timer1.Start();

        }
        private void InitChart()
        {
           
          
            waveformChart.BackColor = _chartBackGroupColor;
            waveformChart.Dock = DockStyle.Fill;
            waveformChart.TextAntiAliasingQuality = System.Windows.Forms.DataVisualization.Charting.TextAntiAliasingQuality.SystemDefault;
            //定义图表区域
            waveformChart.ChartAreas.Clear();
            ChartArea chartArea = new ChartArea("C1");
            waveformChart.ChartAreas.Add(chartArea);
            //定义存储和显示点的容器
            waveformChart.Series.Clear();
            Series series1 = new Series("S1");
            series1.ChartArea = "C1";
            waveformChart.Series.Add(series1);
          
            //设置图表显示样式
            waveformChart.ChartAreas[0].AxisY.Minimum = 0;
            waveformChart.ChartAreas[0].AxisY.Maximum = 100;
            waveformChart.ChartAreas[0].AxisY.Interval = 10;
            waveformChart.ChartAreas[0].AxisX.Minimum = 0;
            waveformChart.ChartAreas[0].AxisX.Maximum = queueCount;
            waveformChart.ChartAreas[0].AxisX.Interval = 1;
            //waveformChart.ChartAreas[0].AxisX.Enabled = AxisEnabled.True;
            waveformChart.ChartAreas[0].AxisY.Enabled = AxisEnabled.True;
            waveformChart.ChartAreas[0].AxisX.LabelStyle.Enabled = false;
            waveformChart.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Silver;
            waveformChart.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Silver;
            //设置标题
            waveformChart.Titles.Clear();
            //waveformChart.Titles.Add("S01");
            //waveformChart.Titles[0].Text = "XXX显示";
            //waveformChart.Titles[0].ForeColor = Color.RoyalBlue;
            //waveformChart.Titles[0].Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
            //设置图表显示样式
            waveformChart.Series[0].Color = Color.Lime;         
            waveformChart.Series[0].ChartType = SeriesChartType.Line;
            waveformChart.Series[0].Points.Clear();
        }
        private Color _chartBackGroupColor = Color.WhiteSmoke;
        [Description("获取或设置Chart的背景颜色"), Category("自定义属性")]
        public Color ChartBackGroupColor
        {
            get
            {
                return _chartBackGroupColor;
            }
            set
            {
                this._chartBackGroupColor = value;
                this.Invalidate();
            }
        }

        private int _refreshRate = 1;
        [Description("获取或设置Chart刷新频率"), Category("自定义属性")]
        public int RefreshRate
        {
            get
            {
                return _refreshRate;
            }
            set
            {
                this._refreshRate = value;
            }
        }

        private int _nextValue = 0;
        [Description("获取或设置Chart的Y轴值"), Category("自定义属性")]
        public int NextValue
        {
            get
            {
                return _nextValue;
            }
            set
            {
                this._nextValue = value;
            }
        }

        private void DoWork()
        {
           
            //for (int i = 0; i < 10; i++)
            //{
            //    System.Threading.Thread.Sleep(1000);
            //}
            NextValue = new Random().Next(0, 100);
            if (!isFirst)
            {
                isFirst = true;
                waveformChart.Series[0].Points.AddXY(0, NextValue);
            }
            UpdateQueueValue();

            waveformChart.Series[0].Points.Clear();

            for (int i = 0; i < dataQueue.Count; i++)
            {

                waveformChart.Series[0].Points.AddXY((i + 1), dataQueue.ElementAt(i));
            }
        }

        private void UpdateQueueValue()
        {
            if (dataQueue.Count > queueCount)
            {                
                    dataQueue.Dequeue();                  
             
                    dataQueue.Enqueue(NextValue);               
              
            }
            else
            {                                 
                    dataQueue.Enqueue(NextValue);
               
            }
        }

    }

5.学习借鉴:

http://www.pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html
http://blog.csdn.net/morewindows/article/details/8678382
http://www.163nvren.com/html/1873031.html
http://www.myexception.cn/c-sharp/1700876.html

版权声明:本文为TBW-Superhero原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:http://www.cnblogs.com/TBW-Superhero/p/7883492.html