2012-08-28 25 views
-1

我想要獲得當前每次使用pc的總體使用情況,比如說每5秒鐘獲取一次cpu使用情況的更新值。我如何獲得個人電腦的CPU使用率和特定的過程?

並每隔5秒獲取特定進程名稱的CPU使用情況的值。例如,我將在運行時選擇哪個進程來獲得CPU的使用。

因此,在運行程序時,我會看到兩個標籤每5秒更新一次。

現在這是我的代碼:

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


namespace CpuUsage 
{ 
    public partial class Form1 : Form 
    { 

     private PerformanceCounter theCPUCounter; 
     private PerformanceCounter theMemCounter; 
     private PerformanceCounter specProcessCPUCounter; 
     private float cpuUsage; 
     private float memUsage; 
     private string processname; 

     public Form1() 
     { 
      InitializeComponent(); 


       theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 
       theMemCounter = new PerformanceCounter("Memory", "Available MBytes"); 
       specProcessCPUCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName); 
       processname = specProcessCPUCounter.CounterName; 
       cpuUsage = this.theCPUCounter.NextValue(); 
       memUsage = theMemCounter.NextValue(); 
       label1.Text = memUsage.ToString(); 


     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

我有設計師label1和label2。 CPUCounter的值始終爲0。 我不知道如何使用specProcessCPUCounter來獲取特定的進程cpuUsage。 而我不知道如何讓他們每5秒就會更新一次。

+3

你明白你的代碼只運行一次。換句話說,它正在做它應該做的事情。我不得不因爲缺乏研究和/或調試而忽略了這個問題。 –

回答

0

您需要添加一個WinForms計時器並更新Tick處理程序中的標籤文本。

相關問題