WPF使用DynamicDataDisplay.dll显示CPU及内存使用曲线

原文: WPF使用DynamicDataDisplay.dll显示CPU及内存使用曲线

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/46875243

DynamicDataDisplay.dll是一个添加动态数据到您的Silverlight或WPF应用程序交互的可视化控件。它允许创建线图,气泡图,热图和其他复杂的二维图,这是非常常见的科学软件。

DynamicDataDisplay sample charts:


下载地址如下:

http://dynamicdatadisplay.codeplex.com/

首先创建一个WPF工程,在引用上右键选择“添加引用”,找到下载好的DynamicDataDisplay.dll;

其次在.cs文件中加入引用集:

using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;

private ObservableDataSource dataSource = new ObservableDataSource(); // 动态存储图表坐标点
private PerformanceCounter cpuPerformance = new PerformanceCounter(); //表示Windows NT的性能组件
private DispatcherTimer timer = new DispatcherTimer();//创建一个定时器
定义一个函数用于获取CPU和内存的数据:

private void AnimatedPlot(object sender, EventArgs e) 

cpuPerformance.CategoryName = "Processor"; 

cpuPerformance.CounterName = "% Processor Time"; 

cpuPerformance.InstanceName = "_Total"; 

double x = i; 

//调试的时候,无法调用NextValue()函数,需要把y赋一个固定的值 

double y = cpuPerformance.NextValue(); 

if (maxCpu < y) 

maxCpu = y; 

//double y = 12; 

double MemoryUse = Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0 / 1024.0; //获取使用内存

Point point = new Point(x, y); 

dataSource.AppendAsync(base.Dispatcher, point); 

cpuUsageText.Text = String.Format("{0:0}%", y); //cpuUsageText为TextBlock控件,显示CPU使用率

cpuMaxText.Text = String.Format("{0:0}%", maxCpu);//cpuMaxText为TextBlock控件,显示CPU最大使用率

memoryUsageText.Text = MemoryUse.ToString("F02");//memoryUsageText为TextBlock控件,显示占用内存大小

i++; 

}

注意:在VS调试代码的过程中,NextValue()函数会报错!!需要将y赋值为常数。

接下来就是显示图像了:

public void StartCpuShow() 

plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage"); //设置图像中线的相关信息

timer.Interval = TimeSpan.FromSeconds(1); 

timer.Tick += new EventHandler(AnimatedPlot); 

timer.IsEnabled = true; plotter.Viewport.FitToView(); 

}


在xaml文件中添加命名空间:

xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
通过<d3:ChartPlotter> 创建一个图表框架;

在其中添加两条整型坐标轴:

X轴:<d3:HorizontalIntegerAxis>

Y轴:<d3:VerticalIntegerAxis>

<d3:Header> 用来设置图表名称

<d3:VerticalAxisTitle> 用来设置Y轴名称。

<d3:ChartPlotter x:Name="plotter" Margin="10,10,33,10" Grid.Row="1" Background="Transparent" Foreground="#FF00DBE7"> 

<d3:ChartPlotter.VerticalAxis> 

<d3:VerticalIntegerAxis Foreground="#FF00DBE7"/>

  </d3:ChartPlotter.VerticalAxis> 

<d3:ChartPlotter.HorizontalAxis > 

<d3:HorizontalIntegerAxis Foreground="#FF00DBE7"/> 

</d3:ChartPlotter.HorizontalAxis> 

<d3:Header Content="CPU Performance History" Foreground="#FF00DBE7"/> 

</d3:ChartPlotter>

最后需要注意的是,很多系统无法运行该程序。注意是需要重建性能计数器才可以使用查看CPU等功能

重建方法如下:

运行cmd 命令行

输入 lodctr/R 

等待重建性能计数器


最后上效果图:


如有疑问 [email protected]


猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9704846.html