CPU 使用率% NotifyIcon 使用 WMI

CPU Usage% NotifyIcon Using WMI

我一直在尝试创建一个任务栏托盘图标,当使用 C# 悬停或单击时,它会显示 CPU 用法(如果可能,从 wbemtest 中提取)。我使用 ManagementClass Win32_PerfFormattedData_Counters_ProcessorInformation 中的 PercentProcessorTime 名称来提取数据。我什至无法找到名称对 return 意味着什么数据类型。我可以从其他地方获取数据吗?

public void CPUactivitythread()
    {
        //Create a management object to open wbemtest
        ManagementClass CPUdataclass = new ManagementClass("Win32_PerfFormattedData_Counters_ProcessorInformation");

        try
        {
            //While Loop to pull consistent data from the CPU
            while (true)
            {
                //Connect to the CPU Performance Instances in wbemtest
                ManagementObjectCollection CPUobjectCollection = CPUdataclass.GetInstances();

                foreach (ManagementObject obj in CPUobjectCollection) {
                    //Check that the "PercentProcessorTime" instance is there
                    if (obj["Name"].ToString() == "PercentProcessorTime")
                    {
                        if (Convert.ToUInt64(obj["PercentProcessorTime"]) > 0)
                        {
                            cPUUsageToolStripMenuItem.Text = (obj["PercentProcessorTime"]).ToString();
                            CPUoutputLabel.Text = (obj["PercentProcessorTime"]).ToString();
                        }
                        else
                        {

                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }

Collection中的对象对应任务管理器CPU信息,每个CPU一个,Total一个,名为“_Total”。 "PercentProcessorTime" 是每个性能对象的 属性。由于你拿到的是Formatted数据,所以已经根据其性能公式进行了计算("cooked"),可以直接使用。如果您不喜欢阅读文档,LINQPad 是一个非常有用的探索对象的工具:)

试试这个:

ManagementClass CPUdataclass = new ManagementClass("Win32_PerfFormattedData_Counters_ProcessorInformation");

try {
    //While Loop to pull consistent data from the CPU
    while (true) {
        //Connect to the CPU Performance Instances in wbemtest
        ManagementObjectCollection CPUobjectCollection = CPUdataclass.GetInstances();

        foreach (ManagementObject obj in CPUobjectCollection) {
            //Check that the "PercentProcessorTime" instance is there
            if (obj["Name"].ToString() == "_Total") {
                var PPT = Convert.ToUInt64(obj.GetPropertyValue("PercentProcessorTime"));
                if (PPT > 0) {
                    cPUUsageToolStripMenuItem.Text = PPT.ToString();
                    CPUoutputLabel.Text = PPT.ToString();
                }
            }
            else {

            }
        }
    }