【C#】获取电脑CPU、内存、屏幕、磁盘等信息

通过WMI类来获取电脑各种信息,参考文章:WMI_04_常见的WMI类的属性_wmi scsilogicalunit_fantongl的博客-CSDN博客

自己整理了获取电脑CPU、内存、屏幕、磁盘等信息的代码

 #region 系统信息

    /// 
    /// 电脑信息
    /// 
    public partial class ComputerInfo
    {
        /// 
        /// 系统版本
        /// 示例:Windows 10 Enterprise
        /// 
        public static string OSProductName { get; } = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", 0);

        /// 
        /// 操作系统版本
        /// 示例:Microsoft Windows 10.0.18363
        /// 
        public static string OSDescription { get; } = System.Runtime.InteropServices.RuntimeInformation.OSDescription;

        /// 
        /// 操作系统架构()
        /// 示例:X64
        /// 
        public static string OSArchitecture { get; } = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString();

        /// 
        /// 获取系统信息
        /// 
        /// 
        public static SystemInfo GetSystemInfo()
        {
            SystemInfo systemInfo = new SystemInfo();

            var osProductName = OSProductName.Trim().Replace(" ", "_");
            var osVersionNames = Enum.GetNames(typeof(OSVersion)).ToList();

            for (int i = 0; i < osVersionNames.Count; i++)
            {
                var osVersionName = osVersionNames[i];
                if (osProductName.Contains(osVersionName))
                {
                    systemInfo.OSVersion = (OSVersion)Enum.Parse(typeof(OSVersion), osVersionName);
                    systemInfo.WindowsVersion = osProductName.Replace(osVersionName, "").Replace("_", " ");
                }
            }

            systemInfo.WindowsVersionNo = OSDescription;
            systemInfo.Architecture = OSArchitecture;

            return systemInfo;
        }
    }

    /// 
    /// 系统信息
    /// 
    public class SystemInfo
    {
        /// 
        /// 系统版本。如:Windows 10
        /// 
        public string WindowsVersion { get; set; }

        /// 
        /// 系统版本。如:专业版
        /// 
        public OSVersion OSVersion { get; set; }
        /// 
        /// Windows版本号。如:Microsoft Windows 10.0.18363
        /// 
        public string WindowsVersionNo { get; set; }
        /// 
        /// 操作系统架构。如:X64
        /// 
        public string Architecture { get; set; }
    }

    /// 
    /// 系统客户版本
    /// 
    public enum OSVersion
    {
        /// 
        /// 家庭版
        /// 
        Home,
        /// 
        /// 专业版,以家庭版为基础
        /// 
        Pro,
        Professional,
        /// 
        /// 企业版,以专业版为基础
        /// 
        Enterprise,
        /// 
        /// 教育版,以企业版为基础
        /// 
        Education,
        /// 
        /// 移动版
        /// 
        Mobile,
        /// 
        /// 企业移动版,以移动版为基础
        /// 
        Mobile_Enterprise,
        /// 
        /// 物联网版
        /// 
        IoT_Core,
        /// 
        /// 专业工作站版,以专业版为基础
        /// 
        Pro_for_Workstations
    }

    #endregion

    #region CPU信息

    public partial class ComputerInfo
    {
        /// 
        /// CPU信息
        /// 
        /// 
        public static CPUInfo GetCPUInfo()
        {
            var cpuInfo = new CPUInfo();
            var cpuInfoType = cpuInfo.GetType();
            var cpuInfoFields = cpuInfoType.GetProperties().ToList();
            var moc = new ManagementClass("Win32_Processor").GetInstances();
            foreach (var mo in moc)
            {
                foreach (var item in mo.Properties)
                {
                    if (cpuInfoFields.Exists(f => f.Name == item.Name))
                    {
                        var p = cpuInfoType.GetProperty(item.Name);
                        p.SetValue(cpuInfo, item.Value);
                    }
                }
            }
            return cpuInfo;
        }
    }

    /// 
    /// CPU信息
    /// 
    public class CPUInfo
    {
        /// 
        /// 操作系统类型,32或64
        /// 
        public uint AddressWidth { get; set; }
        /// 
        /// 处理器的名称。如:Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz
        /// 
        public string Name { get; set; }

        /// 
        /// 处理器的当前实例的数目。如:4。4核
        /// 
        public uint NumberOfEnabledCore { get; set; }
        /// 
        /// 用于处理器的当前实例逻辑处理器的数量。如:4。4线程
        /// 
        public uint NumberOfLogicalProcessors { get; set; }
        /// 
        /// 系统的名称。计算机名称。如:GREAMBWANG
        /// 
        public string SystemName { get; set; }
    }

    #endregion

    #region 内存信息
    public partial class ComputerInfo
    {
        /// 
        /// 内存信息
        /// 
        /// 
        public static RAMInfo GetRAMInfo()
        {
            var ramInfo = new RAMInfo();

            var totalPhysicalMemory = TotalPhysicalMemory;
            var memoryAvailable = MemoryAvailable;

            var conversionValue = 1024.0 * 1024.0 * 1024.0;

            ramInfo.TotalPhysicalMemoryGBytes = Math.Round((double)(totalPhysicalMemory / conversionValue), 1);
            ramInfo.MemoryAvailableGBytes = Math.Round((double)(memoryAvailable / conversionValue), 1);
            ramInfo.UsedMemoryGBytes = Math.Round((double)((totalPhysicalMemory - memoryAvailable) / conversionValue), 1);
            ramInfo.UsedMemoryRatio = (int)(((totalPhysicalMemory - memoryAvailable) * 100.0) / totalPhysicalMemory);

            return ramInfo;
        }

        /// 
        /// 总物理内存(B)
        /// 
        /// 
        public static long TotalPhysicalMemory
        {
            get
            {
                long totalPhysicalMemory = 0;

                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo["TotalPhysicalMemory"] != null)
                    {
                        totalPhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
                    }
                }
                return totalPhysicalMemory;
            }
        }

        /// 
        /// 获取可用内存(B)
        /// 
        public static long MemoryAvailable
        {
            get
            {
                long availablebytes = 0;
                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
                foreach (ManagementObject mo in mos.GetInstances())
                {
                    if (mo["FreePhysicalMemory"] != null)
                    {
                        availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
                    }
                }
                return availablebytes;
            }
        }

    }

    /// 
    /// 内存信息
    /// 
    public class RAMInfo
    {
        /// 
        /// 总物理内存(GB)
        /// 
        public double TotalPhysicalMemoryGBytes { get; set; }
        /// 
        /// 获取可用内存(GB)
        /// 
        public double MemoryAvailableGBytes { get; set; }
        /// 
        /// 获取已用内存(GB)
        /// 
        public double UsedMemoryGBytes { get; set; }
        /// 
        /// 内存使用率
        /// 
        public int UsedMemoryRatio { get; set; }
    }

    #endregion

    #region 屏幕信息

    public partial class ComputerInfo
    {
        /// 
        /// 屏幕信息
        /// 
        public static GPUInfo GetGPUInfo()
        {
            GPUInfo gPUInfo = new GPUInfo();
            gPUInfo.CurrentResolution = MonitorHelper.GetResolution();
            gPUInfo.MaxScreenResolution = GetGPUInfo2();

            return gPUInfo;
        }

        /// 
        /// 获取最大分辨率
        /// 
        /// 
        private static Size GetMaximumScreenSizePrimary()
        {
            var scope = new System.Management.ManagementScope();
            var q = new System.Management.ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");

            UInt32 maxHResolution = 0;
            UInt32 maxVResolution = 0;

            using (var searcher = new System.Management.ManagementObjectSearcher(scope, q))
            {
                var results = searcher.Get();
              
                foreach (var item in results)
                {
                    if ((UInt32)item["HorizontalResolution"] > maxHResolution)
                        maxHResolution = (UInt32)item["HorizontalResolution"];

                    if ((UInt32)item["VerticalResolution"] > maxVResolution)
                        maxVResolution = (UInt32)item["VerticalResolution"];
                }
            }
            return new Size((int)maxHResolution, (int)maxVResolution);
        }

        /// 
        /// 获取最大分辨率2
        /// CurrentHorizontalResolution:1920
        /// CurrentVerticalResolution:1080
        /// 
        /// 
        public static Size GetGPUInfo2()
        {
            var gpu = new StringBuilder();
            var moc = new ManagementObjectSearcher("select * from Win32_VideoController").Get();

            var currentHorizontalResolution = 0;
            var currentVerticalResolution = 0;

            foreach (var mo in moc)
            {
                foreach (var item in mo.Properties)
                {
                    if (item.Name == "CurrentHorizontalResolution" && item.Value != null)
                        currentHorizontalResolution = int.Parse((item.Value.ToString()));
                    if (item.Name == "CurrentVerticalResolution" && item.Value != null)
                        currentVerticalResolution = int.Parse((item.Value.ToString()));
                    //gpu.Append($"{item.Name}:{item.Value}\r\n");
                }
            }
            //var res = gpu.ToString();
            //return res;
            return new Size(currentHorizontalResolution, currentVerticalResolution);
        }

    }

    public class MonitorHelper
    {
        /// 
        /// 获取DC句柄
        /// 
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hdc);
        /// 
        /// 释放DC句柄
        /// 
        [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
        static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hdc);
        /// 
        /// 获取句柄指定的数据
        /// 
        [DllImport("gdi32.dll")]
        static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        /// 
        /// 获取设置的分辨率(修改缩放,该值不改变)
        /// {Width = 1920 Height = 1080}
        /// 
        /// 
        public static Size GetResolution()
        {
            Size size = new Size();
            IntPtr hdc = GetDC(IntPtr.Zero);
            size.Width = GetDeviceCaps(hdc, DeviceCapsType.DESKTOPHORZRES);
            size.Height = GetDeviceCaps(hdc, DeviceCapsType.DESKTOPVERTRES);
            ReleaseDC(IntPtr.Zero, hdc);
            return size;
        }

        /// 
        /// 获取屏幕物理尺寸(mm,mm)
        /// {Width = 476 Height = 268}
        /// 
        /// 
        public static Size GetScreenSize()
        {
            Size size = new Size();
            IntPtr hdc = GetDC(IntPtr.Zero);
            size.Width = GetDeviceCaps(hdc, DeviceCapsType.HORZSIZE);
            size.Height = GetDeviceCaps(hdc, DeviceCapsType.VERTSIZE);
            ReleaseDC(IntPtr.Zero, hdc);
            return size;
        }

        /// 
        /// 获取屏幕的尺寸---inch
        /// 21.5
        /// 
        /// 
        public static float GetScreenInch()
        {
            Size size = GetScreenSize();
            double inch = Math.Round(Math.Sqrt(Math.Pow(size.Width, 2) + Math.Pow(size.Height, 2)) / 25.4, 1);
            return (float)inch;
        }
    }

    /// 
    /// GetDeviceCaps 的 nidex值
    /// 
    public class DeviceCapsType
    {
        public const int DRIVERVERSION = 0;
        public const int TECHNOLOGY = 2;
        public const int HORZSIZE = 4;//以毫米为单位的显示宽度
        public const int VERTSIZE = 6;//以毫米为单位的显示高度
        public const int HORZRES = 8;
        public const int VERTRES = 10;
        public const int BITSPIXEL = 12;
        public const int PLANES = 14;
        public const int NUMBRUSHES = 16;
        public const int NUMPENS = 18;
        public const int NUMMARKERS = 20;
        public const int NUMFONTS = 22;
        public const int NUMCOLORS = 24;
        public const int PDEVICESIZE = 26;
        public const int CURVECAPS = 28;
        public const int LINECAPS = 30;
        public const int POLYGONALCAPS = 32;
        public const int TEXTCAPS = 34;
        public const int CLIPCAPS = 36;
        public const int RASTERCAPS = 38;
        public const int ASPECTX = 40;
        public const int ASPECTY = 42;
        public const int ASPECTXY = 44;
        public const int SHADEBLENDCAPS = 45;
        public const int LOGPIXELSX = 88;//像素/逻辑英寸(水平)
        public const int LOGPIXELSY = 90; //像素/逻辑英寸(垂直)
        public const int SIZEPALETTE = 104;
        public const int NUMRESERVED = 106;
        public const int COLORRES = 108;
        public const int PHYSICALWIDTH = 110;
        public const int PHYSICALHEIGHT = 111;
        public const int PHYSICALOFFSETX = 112;
        public const int PHYSICALOFFSETY = 113;
        public const int SCALINGFACTORX = 114;
        public const int SCALINGFACTORY = 115;
        public const int VREFRESH = 116;
        public const int DESKTOPVERTRES = 117;//垂直分辨率
        public const int DESKTOPHORZRES = 118;//水平分辨率
        public const int BLTALIGNMENT = 119;
    }

    /// 
    /// 屏幕信息
    /// 
    public class GPUInfo
    {
        /// 
        /// 当前分辨率
        /// 
        public Size CurrentResolution { get; set; }
        /// 
        /// 最大分辨率
        /// 
        public Size MaxScreenResolution { get; set; }

    }

    #endregion

    #region 硬盘信息

    public partial class ComputerInfo
    {
        /// 
        /// 磁盘信息
        /// 
        public static List GetDiskInfo()
        {
            List diskInfos = new List();
            try
            {
                var moc = new ManagementClass("Win32_LogicalDisk").GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    var diskInfo = new DiskInfo();
                    var diskInfoType = diskInfo.GetType();
                    var diskInfoFields = diskInfoType.GetProperties().ToList();

                    foreach (var item in mo.Properties)
                    {
                        if (diskInfoFields.Exists(f => f.Name == item.Name))
                        {
                            var p = diskInfoType.GetProperty(item.Name);
                            p.SetValue(diskInfo, item.Value);
                        }
                    }
                    diskInfos.Add(diskInfo);
                }

                //B转GB
                for (int i = 0; i < diskInfos.Count; i++)
                {
                    diskInfos[i].Size = Math.Round((double)(diskInfos[i].Size / 1024.0 / 1024.0 / 1024.0), 1);
                    diskInfos[i].FreeSpace = Math.Round((double)(diskInfos[i].FreeSpace / 1024.0 / 1024.0 / 1024.0), 1);
                }
            }
            catch (Exception ex)
            {

            }

            return diskInfos;
        }
    }

    /// 
    /// 磁盘信息
    /// 
    public class DiskInfo
    {
        /// 
        /// 磁盘ID 如:D:
        /// 
        public string DeviceID { get; set; }
        /// 
        /// 驱动器类型。3为本地固定磁盘,2为可移动磁盘
        /// 
        public uint DriveType { get; set; }
        /// 
        /// 磁盘名称。如:系统
        /// 
        public string VolumeName { get; set; }
        /// 
        /// 描述。如:本地固定磁盘
        /// 
        public string Description { get; set; }
        /// 
        /// 文件系统。如:NTFS
        /// 
        public string FileSystem { get; set; }
        /// 
        /// 磁盘容量(GB)
        /// 
        public double Size { get; set; }
        /// 
        /// 可用空间(GB)
        /// 
        public double FreeSpace { get; set; }

        public override string ToString()
        {
            return $"{VolumeName}({DeviceID}), {FreeSpace}GB is available for {Size}GB in total, {FileSystem}, {Description}";
        }

    }

    #endregion

可以获取下面这些信息:

ComputerCheck Info:
System Info:Windows 10 Enterprise, Enterprise, X64, Microsoft Windows 10.0.18363 
CPU Info:Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz, 4 Core 4 Threads
RAM Info:12/15.8GB(75%)
GPU Info:1920*1080 / 1920*1080
Disk Info:系统(C:), 74.2GB is available for 238.1GB in total, NTFS, 本地固定磁盘
软件(D:), 151.9GB is available for 300GB in total, NTFS, 本地固定磁盘
办公(E:), 30.7GB is available for 300GB in total, NTFS, 本地固定磁盘
其它(F:), 256.3GB is available for 331.5GB in total, NTFS, 本地固定磁盘

参考文章:

WMI_04_常见的WMI类的属性_wmi scsilogicalunit_fantongl的博客-CSDN博客

C#获取计算机物理内存和可用内存大小封装类SystemInfo_c# 获得物理内存大小_CodingPioneer的博客-CSDN博客

https://www.cnblogs.com/pilgrim/p/15115925.html

win10各种版本英文名称是什么? - 编程之家

https://www.cnblogs.com/dongweian/p/14182576.html

C# 使用WMI获取所有服务的信息_c# wmi_FireFrame的博客-CSDN博客

WMI_02_常用WMI查询列表_fantongl的博客-CSDN博客

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