zoukankan      html  css  js  c++  java
  • C# 获取Windows系统:Cpu使用率,内存使用率,Mac地址,磁盘使用率

    一、获取CPU使用率:

     #region 获取CPU使用率
    
            #region AIP声明 
            [DllImport("IpHlpApi.dll")]
            extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
    
            [DllImport("User32")]
            private extern static int GetWindow(int hWnd, int wCmd);
    
            [DllImport("User32")]
            private extern static int GetWindowLongA(int hWnd, int wIndx);
    
            [DllImport("user32.dll")]
            private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
    
            [DllImport("user32", CharSet = CharSet.Auto)]
            private extern static int GetWindowTextLength(IntPtr hWnd);
            #endregion
            
            public static float? GetCpuUsedRate()
            {
                try
                {
                    PerformanceCounter pcCpuLoad;
                    pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
                    {
                        MachineName = "."
                    };
                    pcCpuLoad.NextValue();
                    Thread.Sleep(1500);
                    float CpuLoad= pcCpuLoad.NextValue();
                    
                 return CpuLoad;
                }
                catch
                {
                }
                return 0;
            }
            #endregion

    二、获取内存使用率

    其中ManagementClass类需要手动引用System.Management,然后再using System.Management。

      #region 获取内存使用率
            #region 可用内存
    
            /// <summary>
            ///     获取可用内存
            /// </summary>
            internal static long? GetMemoryAvailable()
            {
               
                 long availablebytes = 0;
                 var managementClassOs = new ManagementClass("Win32_OperatingSystem");
                 foreach (var managementBaseObject in managementClassOs.GetInstances())
                     if (managementBaseObject["FreePhysicalMemory"] != null)
                       availablebytes = 1024 * long.Parse(managementBaseObject["FreePhysicalMemory"].ToString());
                return availablebytes / MbDiv;
                
            }
    
            #endregion
            internal static double? GetMemoryUsed()
            {
                float? PhysicalMemory = GetPhysicalMemory();
                float? MemoryAvailable = GetMemoryAvailable();
                double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
                double currentMemoryUsed = (double)MemoryUsed ;
                return currentMemoryUsed ;
            }
            private static long? GetPhysicalMemory()
            {
                //获得物理内存
                var managementClass = new ManagementClass("Win32_ComputerSystem");
                var managementObjectCollection = managementClass.GetInstances();
                long PhysicalMemory;
                foreach (var managementBaseObject in managementObjectCollection)
                    if (managementBaseObject["TotalPhysicalMemory"] != null)
                    {
                       return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString())/ MbDiv;
                    }
                return null;
    
            }
            public static double? GetMemoryUsedRate()
            {
                float? PhysicalMemory = GetPhysicalMemory();
                float? MemoryAvailable = GetMemoryAvailable();
                double? MemoryUsedRate =(double?)(PhysicalMemory - MemoryAvailable)/ PhysicalMemory;
                return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * 100) : 0;
            }
            #endregion
    
            #region 单位转换进制
    
            private const int KbDiv = 1024;
            private const int MbDiv = 1024 * 1024;
            private const int GbDiv = 1024 * 1024 * 1024;
    
            #endregion

    三、获取Mac地址

    #region 获取当前活动网络MAC地址
            /// <summary>  
            /// 获取本机MAC地址  
            /// </summary>  
            /// <returns>本机MAC地址</returns>  
            public static string GetMacAddress()
            {
                try
                {
                    string strMac = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        if ((bool)mo["IPEnabled"] == true)
                        {
                            strMac = mo["MacAddress"].ToString();
                        }
                    }
                    moc = null;
                    mc = null;
                    return strMac;
                }
                catch
                {
                    return "unknown";
                }
            }
            #endregion

    四、获取磁盘使用率

       #region 获取磁盘占用率
            internal static double GetUsedDiskPercent()
            {
                float? usedSize = GetUsedDiskSize();
                float? totalSize = GetTotalSize();
                double? percent = (double?)usedSize / totalSize;
                return percent.HasValue ? Convert.ToDouble(percent * 100) : 0;
            }
    
            internal static float? GetUsedDiskSize()
            {
                var currentDrive = GetCurrentDrive();
                float UsedDiskSize =(long)currentDrive?.TotalSize - (long)currentDrive?.TotalFreeSpace;
                return UsedDiskSize / MbDiv;
            }
    
            internal static float? GetTotalSize()
            {
                var currentDrive = GetCurrentDrive();
    
                float TotalSize = (long)currentDrive?.TotalSize / MbDiv;
                return TotalSize;
            }
    
            /// <summary>
            /// 获取当前执行的盘符信息
            /// </summary>
            /// <returns></returns>
            private static DriveInfo GetCurrentDrive()
            {
                string path = Application.StartupPath.ToString().Substring(0, 3);
                return DriveInfo.GetDrives().FirstOrDefault<DriveInfo>(p => p.Name.Equals(path));
            }
            #endregion
  • 相关阅读:
    从高版本JDK换成低版本JDK报错Unsupported major.minor version 52.0
    永远不要祈求生活来怜悯你,你只能让自己变的更强
    69 个经典 Spring 面试题和答案
    Jackson 框架,轻易转换JSON
    Apache Commons Codec 编码解码
    演讲
    Shiro源码分析-初始化-Realm
    各个JSON技术的比较
    常见数据库设计(2)——历史数据问题之单记录变更
    fiddler
  • 原文地址:https://www.cnblogs.com/DreamRecorder/p/10218234.html
Copyright © 2011-2022 走看看