C#獲取CPU佔用率、內存佔用、磁盤佔用、進程信息

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Diagnostics;   
  4. using System.Threading;   
  5. using System.IO;   
  6. using System.Text;   
  7. using System.Management;   
  8. using System.Runtime.InteropServices;   
  9.   
  10. namespace Lemony.SystemInfo   
  11. {   
  12.     ///    
  13.     /// 系統信息類 - 獲取CPU、內存、磁盤、進程信息   
  14.     ///    
  15.     public class SystemInfo   
  16.     {   
  17.         private int m_ProcessorCount = 0;   //CPU個數   
  18.         private PerformanceCounter pcCpuLoad;   //CPU計數器   
  19.         private long m_PhysicalMemory = 0;   //物理內存   
  20.   
  21.         private const int GW_HWNDFIRST = 0;   
  22.         private const int GW_HWNDNEXT = 2;   
  23.         private const int GWL_STYLE = (-16);   
  24.         private const int WS_VISIBLE = 268435456;   
  25.         private const int WS_BORDER = 8388608;   
  26.  
  27.         #region API聲明   
  28.         [DllImport("IpHlpApi.dll")]   
  29.         extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);   
  30.   
  31.         [DllImport("User32")]   
  32.         private extern static int GetWindow(int hWnd, int wCmd);   
  33.            
  34.         [DllImport("User32")]   
  35.         private extern static int GetWindowLongA(int hWnd, int wIndx);   
  36.   
  37.         [DllImport("user32.dll")]   
  38.         private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);   
  39.   
  40.         [DllImport("user32", CharSet = CharSet.Auto)]   
  41.         private extern static int GetWindowTextLength(IntPtr hWnd);   
  42.         #endregion   
  43.  
  44.         #region 構造函數   
  45.         ///    
  46.         /// 構造函數,初始化計數器等   
  47.         ///    
  48.         public SystemInfo()   
  49.         {   
  50.             //初始化CPU計數器   
  51.             pcCpuLoad = new PerformanceCounter("Processor""% Processor Time""_Total");   
  52.             pcCpuLoad.MachineName = ".";   
  53.             pcCpuLoad.NextValue();   
  54.   
  55.             //CPU個數   
  56.             m_ProcessorCount = Environment.ProcessorCount;   
  57.   
  58.             //獲得物理內存   
  59.             ManagementClass mc = new ManagementClass("Win32_ComputerSystem");   
  60.             ManagementObjectCollection moc = mc.GetInstances();   
  61.             foreach (ManagementObject mo in moc)   
  62.             {   
  63.                 if (mo["TotalPhysicalMemory"] != null)   
  64.                 {   
  65.                     m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());   
  66.                 }   
  67.             }               
  68.         }    
  69.         #endregion   
  70.  
  71.         #region CPU個數   
  72.         ///    
  73.         /// 獲取CPU個數   
  74.         ///    
  75.         public int ProcessorCount   
  76.         {   
  77.             get   
  78.             {   
  79.                 return m_ProcessorCount;   
  80.             }   
  81.         }   
  82.         #endregion   
  83.  
  84.         #region CPU佔用率   
  85.         ///    
  86.         /// 獲取CPU佔用率   
  87.         ///    
  88.         public float CpuLoad   
  89.         {   
  90.             get   
  91.             {   
  92.                 return pcCpuLoad.NextValue();   
  93.             }   
  94.         }   
  95.         #endregion   
  96.  
  97.         #region 可用內存   
  98.         ///    
  99.         /// 獲取可用內存   
  100.         ///    
  101.         public long MemoryAvailable   
  102.         {   
  103.             get   
  104.             {   
  105.                 long availablebytes = 0;   
  106.                 //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");   
  107.                 //foreach (ManagementObject mo in mos.Get())   
  108.                 //{   
  109.                 //    availablebytes = long.Parse(mo["Availablebytes"].ToString());   
  110.                 //}   
  111.                 ManagementClass mos = new ManagementClass("Win32_OperatingSystem");   
  112.                 foreach (ManagementObject mo in mos.GetInstances())   
  113.                 {   
  114.                     if (mo["FreePhysicalMemory"] != null)   
  115.                     {   
  116.                         availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());   
  117.                     }   
  118.                 }   
  119.                 return availablebytes;   
  120.             }   
  121.         }   
  122.         #endregion   
  123.  
  124.         #region 物理內存   
  125.         ///    
  126.         /// 獲取物理內存   
  127.         ///    
  128.         public long PhysicalMemory   
  129.         {   
  130.             get   
  131.             {   
  132.                 return m_PhysicalMemory;   
  133.             }   
  134.         }   
  135.         #endregion   
  136.  
  137.         #region 獲得分區信息   
  138.         ///    
  139.         /// 獲取分區信息   
  140.         ///    
  141.         public List GetLogicalDrives()   
  142.         {   
  143.             List drives = new List();   
  144.             ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");   
  145.             ManagementObjectCollection disks = diskClass.GetInstances();   
  146.             foreach (ManagementObject disk in disks)   
  147.             {   
  148.                 // DriveType.Fixed 爲固定磁盤(硬盤)   
  149.                 if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)   
  150.                 {   
  151.                     drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString())));   
  152.                 }   
  153.             }   
  154.             return drives;   
  155.         }   
  156.         ///    
  157.         /// 獲取特定分區信息   
  158.         ///    
  159.         /// 盤符   
  160.         public List GetLogicalDrives(char DriverID)   
  161.         {   
  162.             List drives = new List();   
  163.             WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = ’" + DriverID + ":’");   
  164.             ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);   
  165.             foreach (ManagementObject disk in wmifind.Get())   
  166.             {   
  167.                 if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)   
  168.                 {   
  169.                     drives.Add(new DiskInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString())));   
  170.                 }   
  171.             }   
  172.             return drives;   
  173.         }   
  174.         #endregion   
  175.  
  176.         #region 獲得進程列表   
  177.         ///    
  178.         /// 獲得進程列表   
  179.         ///    
  180.         public List GetProcessInfo()   
  181.         {   
  182.             List pInfo = new List();   
  183.             Process[] processes = Process.GetProcesses();   
  184.             foreach (Process instance in processes)   
  185.             {   
  186.                 try   
  187.                 {   
  188.                     pInfo.Add(new ProcessInfo(instance.Id,   
  189.                         instance.ProcessName,   
  190.                         instance.TotalProcessorTime.TotalMilliseconds,   
  191.                         instance.WorkingSet64,   
  192.                         instance.MainModule.FileName));   
  193.                 }   
  194.                 catch { }   
  195.             }   
  196.             return pInfo;   
  197.         }   
  198.         ///    
  199.         /// 獲得特定進程信息   
  200.         ///    
  201.         /// 進程名稱   
  202.         public List GetProcessInfo(string ProcessName)   
  203.         {   
  204.             List pInfo = new List();   
  205.             Process[] processes = Process.GetProcessesByName(ProcessName);   
  206.             foreach (Process instance in processes)   
  207.             {   
  208.                 try   
  209.                 {   
  210.                     pInfo.Add(new ProcessInfo(instance.Id,   
  211.                         instance.ProcessName,   
  212.                         instance.TotalProcessorTime.TotalMilliseconds,   
  213.                         instance.WorkingSet64,   
  214.                         instance.MainModule.FileName));   
  215.                 }   
  216.                 catch { }   
  217.             }   
  218.             return pInfo;   
  219.         }   
  220.         #endregion   
  221.  
  222.         #region 結束指定進程   
  223.         ///    
  224.         /// 結束指定進程   
  225.         ///    
  226.         /// 進程的 Process ID   
  227.         public static void EndProcess(int pid)   
  228.         {   
  229.             try   
  230.             {   
  231.                 Process process = Process.GetProcessById(pid);   
  232.                 process.Kill();   
  233.             }   
  234.             catch { }   
  235.         }   
  236.         #endregion   
  237.        
  238.  
  239.         #region 查找所有應用程序標題   
  240.         ///    
  241.         /// 查找所有應用程序標題   
  242.         ///    
  243.         /// 應用程序標題範型   
  244.         public static List FindAllApps(int Handle)   
  245.         {   
  246.             List Apps = new List();   
  247.   
  248.             int hwCurr;   
  249.             hwCurr = GetWindow(Handle, GW_HWNDFIRST);   
  250.   
  251.             while (hwCurr > 0)   
  252.             {   
  253.                 int IsTask = (WS_VISIBLE | WS_BORDER);   
  254.                 int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);   
  255.                 bool TaskWindow = ((lngStyle & IsTask) == IsTask);   
  256.                 if (TaskWindow)   
  257.                 {   
  258.                     int length = GetWindowTextLength(new IntPtr(hwCurr));   
  259.                     StringBuilder sb = new StringBuilder(2 * length + 1);   
  260.                     GetWindowText(hwCurr, sb, sb.Capacity);   
  261.                     string strTitle = sb.ToString();   
  262.                     if (!string.IsNullOrEmpty(strTitle))   
  263.                     {   
  264.                         Apps.Add(strTitle);   
  265.                     }   
  266.                 }   
  267.                 hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);   
  268.             }   
  269.   
  270.             return Apps;   
  271.         }   
  272.         #endregion        
  273.     }   
  274. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章