System.Diagnostics.PerformanceCounter 提供存取 Windows 效能計數器資料。監控 CPU 使用率需設定:
CategoryName = "Processor"CounterName = "% Processor Time"InstanceName = "_Total"(所有核心平均)或 "0"、"1"...(單核心)
public partial class CpuMonitorForm : Form {
private readonly PerformanceCounter _cpuCounter;
private readonly Timer _timer;
public CpuMonitorForm() {
InitializeComponent();
_cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
_timer = new Timer { Interval = 1000 };
_timer.Tick += Timer_Tick;
_timer.Start();
}
private void Timer_Tick(object sender, EventArgs e) {
float cpu = _cpuCounter.NextValue(); // 首次呼叫回傳 0,後續為百分比
progressBar1.Value = Math.Min(100, (int)cpu);
label1.Text = $"CPU 使用率:{cpu:F1}%";
}
protected override void Dispose(bool disposing) {
if (disposing) {
_timer?.Dispose();
_cpuCounter?.Dispose();
}
base.Dispose(disposing);
}
}
private void InitializeMultiCoreMonitor() {
int coreCount = Environment.ProcessorCount;
var counters = new PerformanceCounter[coreCount];
var bars = new ProgressBar[coreCount];
var labels = new Label[coreCount];
for (int i = 0; i < coreCount; i++) {
counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString(), true);
// 動態建立 UI:GroupBox 包含 Label + ProgressBar
var gb = new GroupBox { Text = $"Core {i}", Dock = DockStyle.Top, Height = 60 };
bars[i] = new ProgressBar { Dock = DockStyle.Fill, Maximum = 100 };
labels[i] = new Label { Dock = DockStyle.Right, Width = 60, TextAlign = ContentAlignment.MiddleRight };
gb.Controls.Add(bars[i]); gb.Controls.Add(labels[i]);
panelContainer.Controls.Add(gb);
}
var timer = new Timer { Interval = 1000 };
timer.Tick += (s, e) => {
for (int i = 0; i < coreCount; i++) {
float v = counters[i].NextValue();
bars[i].Value = Math.Min(100, (int)v);
labels[i].Text = $"{v:F1}%";
}
};
timer.Start();
}
替換 ProgressBar 為第三方儀表控制項(如 Dundas Gauge、LiveCharts、Microcharts),即可呈現儀表板風格 CPU 監控。
Performance Monitor Users 群組new PerformanceCounter(..., machineName: "Server01")NextValue() 首次呼叫回傳 0,建議啟動時呼叫一次捨棄
var searcher = new ManagementObjectSearcher("SELECT LoadPercentage FROM Win32_Processor");
foreach (var obj in searcher.Get()) {
Console.WriteLine($"CPU Load: {obj["LoadPercentage"]}%");
}
WMI 查詢較慢,適合低頻輪詢;PerformanceCounter 適合高頻即時顯示。