C# 获取CPU信息源码 ManagementClass

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication14
{
    public static class CCpuInfo
    {
        public static List myCpu = new List();
        static CCpuInfo()
        {
            ManagementClass mc = new ManagementClass("Win32_processor");

            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject obj in moc)
            {
                myCpu.Add(obj);
            }
        }

        public static int Count
        {
            get
            {
                return myCpu.Count;
            }
        }

        //CPU核心数量
        public static uint GetNumberOfCores(int index = 0)
        {
            if (index >= 0 && index < myCpu.Count)
            {
                return Convert.ToUInt32(myCpu[index].GetPropertyValue("NumberOfCores"));
            }
            else
            {
                return 0U;
            }
        }

        //CPU名称
        public static string GetName(int index = 0)
        {
            if (index >= 0 && index < myCpu.Count)
            {
                return myCpu[index].GetPropertyValue("Name").ToString();
            }
            else
            {
                return "空";
            }
        }

        //CPU所有属性
        public static List GetAllNames(int index = 0)
        {
            List propertyNames = new List();
            if (index >= 0 && index < myCpu.Count)
            {
                foreach (PropertyData data in myCpu[index].Properties)
                {
                    propertyNames.Add(data.Name);
                }
            }

            return propertyNames;
        }
    }
}
 

你可能感兴趣的:(C#)