1.新建一个WinForm工程:
2.找到工具箱中的数据下面的Chart控件,拖拽到界面上去。
3.在属性里面修改Chart控件Name为cpuChart
4.修改series属性,ChartType选为Spline.
5.最后再加个Button按钮,启动曲线绘制。后台代码Form1.cs如下所示:
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; using System.Threading; using System.Diagnostics; namespace CPU_usage { public partial class Form1 : Form { private Thread cpuThread; private double[] cpuArray = new double[80]; public Form1() { InitializeComponent(); } private void getPerformanceCounters() { var cpuPerfCounter = new PerformanceCounter("Processor Information", "% Processor Time", "_Total"); while(true) { cpuArray[cpuArray.Length - 1] = Math.Round(cpuPerfCounter.NextValue(), 0); Array.Copy(cpuArray, 1, cpuArray, 0, cpuArray.Length - 1); if (cpuChart.IsHandleCreated) { this.Invoke((MethodInvoker)delegate { UpdateCpuChart(); }); } else { //...... } Thread.Sleep(100); } } private void UpdateCpuChart() { cpuChart.Series["CPU使用率"].Points.Clear(); for (int i = 0; i < cpuArray.Length - 1; ++i) { cpuChart.Series["CPU使用率"].Points.AddY(cpuArray[i]); } } private void button1_Click(object sender, EventArgs e) { cpuThread = new Thread(new ThreadStart(this.getPerformanceCounters)); cpuThread.IsBackground = true; cpuThread.Start(); } } }
6.编译运行,如下图所示: