首页 新闻 会员 周边

C# 用winAPI获取CPU使用率

0
悬赏园豆:20 [已解决问题] 解决于 2017-01-04 11:35

  开始用PerformanceCounter来获取正常,现在总是报输入字符格式出错!检查了也没问题。

现在想改用winAPI来获取,问用那些API获取信息来计算。只知道有一个GetSystemInfo

来获取CPU的信息。

metoer的主页 metoer | 初学一级 | 园豆:8
提问于:2016-08-19 11:09
< >
分享
最佳答案
0

使用PerformanceCounter:

        using System.Diagnostics;

        public float GetCpuUsage()
        {
            var cpuCounter = new PerformanceCounter
            {
                CategoryName = "Processor",
                CounterName = "% Processor Time",
                InstanceName = "_Total"
            };
            return cpuCounter.NextValue();
        }


使用WMI:

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
  public class MyWMIQuery
  {
    public static void Main()
    {
        try
        {
            ManagementObjectSearcher searcher = 
                new ManagementObjectSearcher("root\\CIMV2", 
                "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process"); 

            foreach (ManagementObject queryObj in searcher.Get())
            {
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Name: {0}", queryObj["Name"]);
                Console.WriteLine("PercentProcessorTime: {0}", queryObj["PercentProcessorTime"]);
            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
        }
    }
  }
}

// 引用来源 http://stackoverflow.com/questions/22195277/get-the-cpu-usage-of-each-process-from-wmi
收获园豆:20
虾。 | 菜鸟二级 |园豆:257 | 2016-08-19 12:55
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册