CPU 使用率% 使用 WMI 通知图标



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

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);
            }
        }
集合

中的对象对应于任务管理器 CPU 信息,每个 CPU 一个,总计一个名为"_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 {
            }
        }
    }

最新更新