c# 获取电脑cpu、内存信息

/// 
    /// 电脑信息操作类
    /// 
    public class ComputerTool
    {
        /// 
        /// 需要初始化才能使用
        /// 
        static PerformanceCounter pcCpuLoad;   //CPU计数器

        static ComputerTool()
        {
            Task.Factory.StartNew(() =>
            {
                //初始化CPU计数器 
                pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                pcCpuLoad.MachineName = ".";
                pcCpuLoad.NextValue();
            });
        }

        /// 
        /// 获取内存最大容量
        /// 字节
        /// 
        /// 
        public static Int64 GetMemory()
        {
            using (ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    return Convert.ToInt64(obj["TotalPhysicalMemory"]);
                }
            }

            return 0;
        }

        /// 
        /// 获取可用内存
        /// MB
        /// 
        /// 
        public static long GetAvailableMemory()
        {
            using (PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes"))
            {
                return ramCounter.NextSample().RawValue;
            }
        }

        /// 
        /// 获取已用内存
        /// 比例
        /// 
        /// 
        public static float GetCommittedMemory()
        {
            using (PerformanceCounter ramCounter = new PerformanceCounter("Memory", "% Committed Bytes In Use"))
            {
                return ramCounter.NextValue();
            }  
        }

        /// 
        /// 得到cpu使用率
        /// 
        /// 
        public static float GetCpu()
        {
            return pcCpuLoad.NextValue();
        }
    }

你可能感兴趣的:(c#,开发语言)