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

这篇具有很好参考价值的文章主要介绍了【C#】获取电脑CPU、内存、屏幕、磁盘等信息。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

 #region 系统信息

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

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

        /// <summary>
        /// 操作系统架构(<see cref="Architecture">)
        /// <para>示例:X64</para>
        /// </summary>
        public static string OSArchitecture { get; } = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString();

        /// <summary>
        /// 获取系统信息
        /// </summary>
        /// <returns></returns>
        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;
        }
    }

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

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

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

    #endregion

    #region CPU信息

    public partial class ComputerInfo
    {
        /// <summary>
        /// CPU信息
        /// </summary>
        /// <returns></returns>
        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;
        }
    }

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

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

    #endregion

    #region 内存信息
    public partial class ComputerInfo
    {
        /// <summary>
        /// 内存信息
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 总物理内存(B)
        /// </summary>
        /// <returns></returns>
        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;
            }
        }

        /// <summary>
        /// 获取可用内存(B)
        /// </summary>
        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;
            }
        }

    }

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

    #endregion

    #region 屏幕信息

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

            return gPUInfo;
        }

        /// <summary>
        /// 获取最大分辨率
        /// </summary>
        /// <returns></returns>
        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);
        }

        /// <summary>
        /// 获取最大分辨率2
        /// CurrentHorizontalResolution:1920
        /// CurrentVerticalResolution:1080
        /// </summary>
        /// <returns></returns>
        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
    {
        /// <summary>
        /// 获取DC句柄
        /// </summary>
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hdc);
        /// <summary>
        /// 释放DC句柄
        /// </summary>
        [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
        static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hdc);
        /// <summary>
        /// 获取句柄指定的数据
        /// </summary>
        [DllImport("gdi32.dll")]
        static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        /// <summary>
        /// 获取设置的分辨率(修改缩放,该值不改变)
        /// {Width = 1920 Height = 1080}
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 获取屏幕物理尺寸(mm,mm)
        /// {Width = 476 Height = 268}
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 获取屏幕的尺寸---inch
        /// 21.5
        /// </summary>
        /// <returns></returns>
        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;
        }
    }

    /// <summary>
    /// GetDeviceCaps 的 nidex值
    /// </summary>
    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;
    }

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

    }

    #endregion

    #region 硬盘信息

    public partial class ComputerInfo
    {
        /// <summary>
        /// 磁盘信息
        /// </summary>
        public static List<DiskInfo> GetDiskInfo()
        {
            List<DiskInfo> diskInfos = new List<DiskInfo>();
            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;
        }
    }

    /// <summary>
    /// 磁盘信息
    /// </summary>
    public class DiskInfo
    {
        /// <summary>
        /// 磁盘ID 如:D:
        /// </summary>
        public string DeviceID { get; set; }
        /// <summary>
        /// 驱动器类型。3为本地固定磁盘,2为可移动磁盘
        /// </summary>
        public uint DriveType { get; set; }
        /// <summary>
        /// 磁盘名称。如:系统
        /// </summary>
        public string VolumeName { get; set; }
        /// <summary>
        /// 描述。如:本地固定磁盘
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 文件系统。如:NTFS
        /// </summary>
        public string FileSystem { get; set; }
        /// <summary>
        /// 磁盘容量(GB)
        /// </summary>
        public double Size { get; set; }
        /// <summary>
        /// 可用空间(GB)
        /// </summary>
        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博客文章来源地址https://www.toymoban.com/news/detail-645073.html

到了这里,关于【C#】获取电脑CPU、内存、屏幕、磁盘等信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 查看centos的CPU、内存、磁盘空间等配置信息

    前置: MemTotal: 系统从加电开始到引导完成,kernel本身要占用一些内存,最后剩下可供kernel支配的内存就是MemTotal。这个值在系统运行期间一般是固定不变的 MemFree: 表示系统尚未使用的内存。[MemTotal-MemFree]就是已被用掉的内存 MemAvailable: 有些应用程序会根据系统的可用内存大

    2024年01月17日
    浏览(18)
  • 【Linux】查看系统各种信息的常用命令 (CPU、内存、进程、网口、磁盘、硬件、等等)

    Linux是一种开源的类Unix操作系统,它有很多不同的发行版,如Ubuntu、CentOS、Debian等。Linux系统提供了很多命令行工具,可以让用户方便地查看和管理系统的各种信息,如硬件配置、内存使用、进程状态、网络连接等。本文将介绍一些常用的命令,以及它们的用法和示例。 使用

    2024年02月15日
    浏览(12)
  • go获取服务器信息(主机、CPU、内存、硬盘)

    使用 github.com/shirou/gopsutil 库来获取机器信息,您可以按照以下步骤进行:

    2024年02月09日
    浏览(18)
  • java获取当前服务器状态cpu、内存、存储等核心信息

    目录 1.需要导入依赖包  2.系统自带参数 3.获取当前服务器状态cpu、内存、存储等核心信息  4.引入包后方法不存在  5. 获取的cpu利用率和任务管理器cpu利用率值差距问题   RESULT: RESULT:  需要引入下面的包:  就是需要配置在 CentralProcessor 实例化之前:配置上也会有差距,相

    2024年02月03日
    浏览(19)
  • Java 使用oshi获取当前服务器状态cpu、内存、存储等核心信息

    OSHI 是基于 JNA 的(本地)操作系统和硬件信息库。它不需要安装任何其他额外的本地库,旨在提供一种跨平台的实现来检索系统信息,例如操作系统版本、进程、内存和 CPU 使用率、磁盘和分区、设备、传感器等。 使用 OSHI 可以对应用程序进行监控,可以对应用程序所在的服

    2024年02月03日
    浏览(19)
  • Python 获取windows下硬件数据信息(CPU,内存,英特尔、英伟达、AMD显卡使用率及详细信息)

    前言:最近一直在做关于显卡数据采集的调研工作,也在github上看到了一些三方库比如Python和golang的psutil, python: gpustart,再或者通过wmi或者windowsApi等底层接口 但是都只能获取到显卡的名称以及厂家信息等 无法真正意义上获取到显卡占用率等数据 在或者只能获取到英伟达的显卡

    2024年02月16日
    浏览(19)
  • 【驱动系列】C#获取电脑硬件显卡核心代号信息

    欢迎来到《小5讲堂》,大家好,我是全栈小5。 这是《驱动系列》文章,每篇文章将以博主理解的角度展开讲解, 特别是针对知识点的概念进行叙说,大部分文章将会对这些概念进行实际例子验证,以此达到加深对知识点的理解和掌握。 温馨提示:博主能力有限,理解水平

    2024年02月21日
    浏览(19)
  • IT涨知识:CPU、内存、磁盘

    CPU: CPU是电子计算机的主要设备之一,电脑中的核心配件。其功能主要是解释计算机指令以及处理计算机软件中的数据。CPU是计算机中负责读取指令,对指令译码并执行指令的核心部件。 CPU使用率过高会怎样:CPU使用率过高会影响处理速度,从而使电脑运行缓慢。如果CPU达

    2024年02月02日
    浏览(8)
  • Jmeter性能指标监控:CPU、内存、磁盘、网络

    jmeter版本:jmeter5.1.1 插件资源(可自己官网下载或从以下网盘中获取): 链接:https://pan.baidu.com/s/1vBr85BLuhhENrnWrFTDGhg 提取码:ywr4 获取插件的最简单方法是安装Plugins Manager,然后只需在Jmeter中单击复选框即可安装任何其他插件。 1)下载 jmeter-plugins-manager-1.3.jar文件 下载地址:

    2024年02月08日
    浏览(18)
  • Linux性能基础:CPU、内存、磁盘等概述

    目录 1. CPU 1.1. CPU常见品牌 1.2. CPU性能概述 ① CPU主频 ② CPU位数 ③ CPU缓存指令集 ④ CPU核心数 ⑤ IPC 1.3. 上下文切换 1.4. 进程与线程 ① 进程 ② 线程 2. 内存 2.1. 内存主频 2.2. 内存带宽 2.3. 内存分类 2.4. 内存的分配 2.5. 内存的回收 2.6. 内存泄漏 3. 磁盘 3.1. 磁盘的构成 3.2. 磁盘

    2023年04月11日
    浏览(11)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包