開発環境 Microsoft Visual Studio Community 2019
実行環境 Microsoft Windows 10 Home (64bit)
プロジェクト テンプレート Windows フォーム アプリケーション (.NET Framework)
プロジェクト名 CpuUsage

コモン コントロール
  • Label
  • NotifyIcon
コンポーネント
  • Timer

Form1.cs
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
 
namespace CpuUsage
{
    public partial class Form1 : Form
    {
        private PerformanceCounter pc;
        private Icon[] icons;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            icons = new Icon[3];
 
            Bitmap bmp = new Bitmap(16, 16);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                for (int i = 0; i < 3; i++)
                {
                    int h = i * 8;
                    g.Clear(Color.Black);
                    g.FillRectangle(Brushes.Lime, 0, 16 - h, 16, h);
                    icons[i] = Icon.FromHandle(bmp.GetHicon());
                }
            }
 
            timer1.Tick += Timer1_Tick;
            timer1.Interval = 1000;
            timer1.Start();
        }
 
        private void Timer1_Tick(object sender, EventArgs e)
        {
            float cpu = pc.NextValue();
            int idx;
            if (cpu < 10) { idx = 0; }
            else if (cpu < 90) { idx = 1; }
            else { idx = 2; }
 
            label1.Text = $"CPU使用率: {Math.Floor(cpu)}%";
            notifyIcon1.Icon = icons[idx];
        }
    }
}
 
最終更新:2020年08月21日 18:37