Thursday, April 2, 2015

C# 프로세스별 CPU 사용률 구하기

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GetProcesses();
        }
        public static void GetProcesses()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

            StreamWriter SW;
            SW = File.CreateText("c:\\MyTextFile.txt");
            foreach (ManagementObject queryObj in searcher.Get())
            {
                SW.Write("Name: {0} ", queryObj["Name"]);
                SW.Write("ProcessID: {0} ", queryObj["IDProcess"]);
                SW.Write("Handles: {0} ", queryObj["HandleCount"]);
                SW.Write("Threads: {0} ", queryObj["ThreadCount"]);
                SW.Write("Memory: {0} ", queryObj["WorkingSetPrivate"]);
                SW.WriteLine("CPU%: {0}", queryObj["PercentProcessorTime"]);
            }
            SW.Close();

        }
    }
}

No comments:

Post a Comment