• 使用WPF动态显示CPU使用率


    使用WPF动态显示CPU使用率

     开源框架  admin  9个月前 (07-14)  1337浏览

    使用WPF动态显示CPU使用率

    基于WPF的开源图表控件有很多,大多数都是静态图表,如果需要绘制CPU使用率这样的动态数据就显得力不从心,微软开源的DynamicDataDisplay控件弥补了这个不足,为了做个备忘,我用它来实时绘制CPU使用率曲线,当然,这个控件也可以绘制动态线图、气泡图和热力图,具体可参阅官网示例代码,使用方法非常简单,下面就直接贴代码,文本末尾提供VS2013的示例代码下载。

    1、首先需要在项目中引用DynamicDataDisplay.dll,该程序集可通过官网下载或者NuGet方式搜索获去,在包控制台执行以下命令即可自动引用。

    PM> Install-Package DynamicDataDisplay

    2、在XAML文件中引用D3命名空间,同时添加一个名为ChartPlotter的图表控件。

    <Window x:Class="WpfCpuUsageSample.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
            Title="MainWindow" Loaded="Window_Loaded" Height="350" Width="525">
        <Grid>
            <d3:ChartPlotter Grid.Column="0" Grid.Row="0"  Name="plotter"/>
        </Grid>
    </Window>
    

    3、在后台窗体类中申明数据源ObservableDataSource用于为图表控件提供数据,PerformanceCounter是性能计数器,可通过它来获取CPU使用率,DispatcherTimer是一个基于WPF的计时器,支持在子线程异步通知UI线程,在窗口加载事件中初始化这些类,并未计时器绑定一个处理程序,用于获取CPU使用率,并将当前的使用率加入到动态曲线中。

    public partial class MainWindow : Window
    {
        private ObservableDataSource<Point> dataSource = new ObservableDataSource<Point>();
        private PerformanceCounter performanceCounter = new PerformanceCounter();
        private DispatcherTimer dispatcherTimer = new DispatcherTimer();
        private int currentSecond = 0;
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            plotter.AddLineGraph(dataSource, Colors.Green, 2, "Percentage");
            plotter.LegendVisible = false;
            dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            dispatcherTimer.Tick += timer_Tick;
            dispatcherTimer.IsEnabled = true;
            plotter.Viewport.FitToView();
        }
    
        private void timer_Tick(object sender, EventArgs e)
        {
            performanceCounter.CategoryName = "Processor";
            performanceCounter.CounterName = "% Processor Time";
            performanceCounter.InstanceName = "_Total";
    
            double x = currentSecond;
            double y = performanceCounter.NextValue();
    
            Point point = new Point(x, y);
            dataSource.AppendAsync(base.Dispatcher, point);
    
            currentSecond++;
        }
    }
  • 相关阅读:
    SQL2005 SQL2008 远程连接配置方法
    Subvision 安装 部署 TortoiseSVN
    在wpf或winform关闭子窗口或对子窗口进行某个操作后刷新父窗口
    C# 中的委托和事件
    长数字隔三位用逗号","隔开,保留两位小数,指定长度,不足补空格
    C# 柱状图, 折线图, 扇形图
    如何在Visual Studio 2010旗舰版本下安装Window Phone 7 简体中文开发环境
    vs2010发布、打包安装程序(超全超详细)
    java 环境搭建
    SQL2008 转 2000(高版本转换到低版本)
  • 原文地址:https://www.cnblogs.com/liyancheng/p/5406574.html
Copyright © 2020-2023  润新知