2013-12-10 93 views
-3

我有這樣的代碼:C#自動CPU使用率刷新

private void button1_Click(object sender, EventArgs e) 
    { 
     PerformanceCounter cpuCounter = new PerformanceCounter(); 
     cpuCounter.CategoryName = "Processor"; 
     cpuCounter.CounterName = "% Processor Time"; 
     cpuCounter.InstanceName = "_Total"; 
     PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 
     var unused = cpuCounter.NextValue(); // first call will always return 0 
     System.Threading.Thread.Sleep(1000); 

     label1.Text = "Cpu usage: :" + cpuCounter.NextValue() + "%"; 
     label2.Text = "Free ram : " + ramCounter.NextValue() + "MB"; 
    } 

怎麼寫程序,而不是通過按下一個按鈕自動更改%的CPU利用率?

回答

1

如果您想模擬ButtonClick事件,您可以使用Timer控制。

第1步:您需要訂閱Timer Tick活動。
步驟2:TimerInterval屬性設置爲1000毫秒,以便每1秒引發一次事件。
第3步:Tick Event Handler只需撥打Button Click事件處理程序。
第4步:只要你想停止定時器,你可以調用timer1.Stop()方法。

試試這個:

System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer(); 
timer1.Interval=1000;//one second 
timer1.Tick += new System.EventHandler(timer1_Tick); 
timer1.Start(); 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    //Call the Button1 Click Event Handler 
    button1_Click(sender,e); 

    //Stop Timer whenever you want. 
    //timer1.Stop(); 
} 
1

您需要使用Timer作任務再次發生。另外要解決「首次調用總是返回0」的問題,只需重新使用同一個性能計數器,每次調用該定時器。

public MyForm() 
{ 
    InitializeComponent(); 

    cpuCounter = new PerformanceCounter(); 
    cpuCounter.CategoryName = "Processor"; 
    cpuCounter.CounterName = "% Processor Time"; 
    cpuCounter.InstanceName = "_Total"; 
    ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 


    //It is better to add the timer via the Design View so it gets disposed properly when the form closes. 
    //timer = new System.Windows.Forms.Timer(); 

    //This setup can be done in the design view too, you just need to call timer.Start() at the end of your constructor (On form load would be even better however, ensures all of the controls have their handles created). 
    timer.Interval=1000; 
    timer.Tick += Timer_Tick; 
    timer.Start(); 
} 

//private System.Windows.Forms.Timer timer; //Added via Design View 

private PerformanceCounter cpuCounter; 
private PerformanceCounter ramCounter; 


private void Timer_Tick(object sender, EventArgs e) 
{ 
    label1.Text = "Cpu usage: :" + cpuCounter.NextValue() + "%"; 
    label2.Text = "Free ram : " + ramCounter.NextValue() + "MB"; 
}