using System;
using System.Drawing;
using System.Management;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SystemMonitor
{
public partial class Form1 : Form
{
private bool _running = true;
public Form1()
{
InitializeComponent();
StartMonitoring();
}
private async void StartMonitoring()
{
while (_running)
{
await Task.Run(() => UpdateSystemInfo());
await Task.Delay(1500);
}
}
private void UpdateSystemInfo()
{
float cpuLoad = GetCpuLoad();
(ulong usedMem, ulong totalMem) = GetMemoryInfo();
this.Invoke((MethodInvoker)delegate
{
// CPU
progressBarCPU.Value = (int)Math.Min(cpuLoad, 100);
labelCPU.Text = $"CPU: {cpuLoad:F1}%";
// RAM
int percentMem = (int)(usedMem * 100 / totalMem);
progressBarRAM.Value = percentMem;
labelRAM.Text = $"RAM: {usedMem} / {totalMem} MB";
// Перерисовка графика
panelGraph.Invalidate();
});
_cpuValue = cpuLoad;
_ramUsed = usedMem;
_ramTotal = totalMem;
}
private float GetCpuLoad()
{
float load = 0;
using (var searcher = new ManagementObjectSearcher("select LoadPercentage from Win32_Processor"))
{
foreach (var obj in searcher.Get())
{
load = Convert.ToSingle(obj["LoadPercentage"]);
}
}
return load;
}
private (ulong used, ulong total) GetMemoryInfo()
{
ulong total = 0;
ulong free = 0;
using (var searcher = new ManagementObjectSearcher("select TotalVisibleMemorySize, FreePhysicalMemory from Win32_OperatingSystem"))
{
foreach (var obj in searcher.Get())
{
total = Convert.ToUInt64(obj["TotalVisibleMemorySize"]) / 1024;
free = Convert.ToUInt64(obj["FreePhysicalMemory"]) / 1024;
}
}
ulong used = total - free;
return (used, total);
}
private float _cpuValue;
private ulong _ramUsed;
private ulong _ramTotal;
private void panelGraph_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int width = panelGraph.Width;
int height = panelGraph.Height;
// CPU bar
int cpuHeight = (int)(_cpuValue / 100 * height);
g.FillRectangle(Brushes.Red, 10, height - cpuHeight, 50, cpuHeight);
// RAM bar
float ramPercent = (float)_ramUsed / _ramTotal;
int ramHeight = (int)(ramPercent * height);
g.FillRectangle(Brushes.Blue, 80, height - ramHeight, 50, ramHeight);
// Подписи
g.DrawString("CPU", Font, Brushes.Black, 10, 5);
g.DrawString("RAM", Font, Brushes.Black, 80, 5);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_running = false;
base.OnFormClosing(e);
}
}
}