1

我一直在尝试创建一个任务栏托盘图标,wbemtest当将鼠标悬停在或单击 using 时显示 CPU 使用率(如果可能的话)C#。我使用了PercentProcessorTimeNameManagementClass Win32_PerfFormattedData_Counters_ProcessorInformation来提取数据。我无法找到 Name 甚至要返回的数据类型。还有其他地方我可以从中获取数据吗?

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);
            }
        }
4

1 回答 1

1

Collection 中的对象对应于Task Manager CPU Information,每个CPU 一个,Total 一个,名为“_Total”。“PercentProcessorTime”是每个性能对象的属性。由于您获得的是格式化数据,因此它已经根据其性能公式计算(“熟”)并且可以直接使用。如果您不喜欢阅读文档,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 {

            }
        }
    }
于 2018-01-24T23:06:21.210 回答