[VC2008] PerformanceCounterを利用して物理空き容量を取得方法

◆概要

 PerformanceCounterを利用すると、物理空き容量を簡単に取得することができます。

 フォームにラベル「lable1」とタイマー「timer1」を配置します。

◆コード

using System;
using System.Windows.Forms;

namespace PerformanceCounterMemory
{
    public partial class Form1 : Form
    {
        System.Diagnostics.PerformanceCounter pc 
                = new System.Diagnostics.PerformanceCounter();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // カテゴリはメモリー
            pc.CategoryName = "memory";

            // 物理空き容量を取得
            pc.CounterName = "Available MBytes";

            // 対象はローカルPC
            pc.MachineName = ".";

            // 100ミリ秒間隔でタイマー設定
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 100;
            timer1.Enabled = true;

        }
        void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = pc.NextValue() + "MB";
        }
    }
}

◆実行結果
実行結果

▼ページトップへ