[No0000112]ComputerInfo,C#获取计算机信息(cpu使用率,内存占用率,硬盘,网络信息)...

github地址:https://github.com/charygao/SmsComputerMonitor

软件用于实时监控当前系统资源等情况,并调用接口,当资源被超额占用时,发送警报到个人手机;界面模拟Console的显示方式,信息缓冲大小由配置决定;可以定制监控的资源,包括:

  • cpu使用率;
  • 内存使用率;
  • 磁盘使用率;
  • 网络使用率;
  • 进程线程数;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;namespace SmsComputerMonitor
{public class ComputerInfo{#region Fields and Propertiesprivate readonly ManagementScope _LocalManagementScope;private readonly PerformanceCounter _pcCpuLoad; //CPU计数器,全局private const int GwHwndfirst = 0;private const int GwHwndnext = 2;private const int GwlStyle = -16;private const int WsBorder = 8388608;private const int WsVisible = 268435456;#region CPU占用率/// <summary>///     获取CPU占用率(系统CPU使用率)/// </summary>public float CpuLoad => _pcCpuLoad.NextValue();#endregion#region 本地主机名public string HostName => Dns.GetHostName();#endregion#region 本地IPV4列表public List<IPAddress> IpAddressV4S{get{var ipV4S = new List<IPAddress>();foreach (var address in Dns.GetHostAddresses(Dns.GetHostName()))if (address.AddressFamily == AddressFamily.InterNetwork)ipV4S.Add(address);return ipV4S;}}#endregion#region 本地IPV6列表public List<IPAddress> IpAddressV6S{get{var ipV6S = new List<IPAddress>();foreach (var address in Dns.GetHostAddresses(Dns.GetHostName()))if (address.AddressFamily == AddressFamily.InterNetworkV6)ipV6S.Add(address);return ipV6S;}}#endregion#region 可用内存/// <summary>///     获取可用内存/// </summary>public long MemoryAvailable{get{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;}}#endregion#region 物理内存/// <summary>///     获取物理内存/// </summary>public long PhysicalMemory { get; }#endregion#region CPU个数/// <summary>///     获取CPU个数/// </summary>// ReSharper disable once UnusedAutoPropertyAccessor.Globalpublic int ProcessorCount { get; }#endregion#region 已用内存大小public long SystemMemoryUsed => PhysicalMemory - MemoryAvailable;#endregion#endregion#region  Constructors/// <summary>///     构造函数,初始化计数器等/// </summary>public ComputerInfo(){_LocalManagementScope = new ManagementScope($"\\\\{HostName}\\root\\cimv2");//初始化CPU计数器_pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total") {MachineName = "."};_pcCpuLoad.NextValue();//CPU个数ProcessorCount = Environment.ProcessorCount;//获得物理内存var managementClass = new ManagementClass("Win32_ComputerSystem");var managementObjectCollection = managementClass.GetInstances();foreach (var managementBaseObject in managementObjectCollection)if (managementBaseObject["TotalPhysicalMemory"] != null)PhysicalMemory = long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString());}#endregion#region  Methods#region 结束指定进程/// <summary>///     结束指定进程/// </summary>/// <param name="pid">进程的 Process ID</param>public static void EndProcess(int pid){try{var process = Process.GetProcessById(pid);process.Kill();}catch (Exception exception){Console.WriteLine(exception);}}#endregion#region 查找所有应用程序标题/// <summary>///     查找所有应用程序标题/// </summary>/// <returns>应用程序标题范型</returns>public static List<string> FindAllApps(int handle){var apps = new List<string>();var hwCurr = GetWindow(handle, GwHwndfirst);while (hwCurr > 0){var IsTask = WsVisible | WsBorder;var lngStyle = GetWindowLongA(hwCurr, GwlStyle);var taskWindow = (lngStyle & IsTask) == IsTask;if (taskWindow){var length = GetWindowTextLength(new IntPtr(hwCurr));var sb = new StringBuilder(2 * length + 1);GetWindowText(hwCurr, sb, sb.Capacity);var strTitle = sb.ToString();if (!string.IsNullOrEmpty(strTitle))apps.Add(strTitle);}hwCurr = GetWindow(hwCurr, GwHwndnext);}return apps;}#endregionpublic static List<PerformanceCounterCategory> GetAllCategories(bool isPrintRoot = true,bool isPrintTree = true){var result = new List<PerformanceCounterCategory>();foreach (var category in PerformanceCounterCategory.GetCategories()){result.Add(category);if (isPrintRoot){PerformanceCounter[] categoryCounters;switch (category.CategoryType){case PerformanceCounterCategoryType.SingleInstance:categoryCounters = category.GetCounters();PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.MultiInstance:var categoryCounterInstanceNames = category.GetInstanceNames();if (categoryCounterInstanceNames.Length > 0){categoryCounters = category.GetCounters(categoryCounterInstanceNames[0]);PrintCategoryAndCounters(category, categoryCounters, isPrintTree);}break;case PerformanceCounterCategoryType.Unknown:categoryCounters = category.GetCounters();PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;//default: break;
                    }}}return result;}/// <summary>///     获取本地所有磁盘/// </summary>/// <returns></returns>public static DriveInfo[] GetAllLocalDriveInfo(){return DriveInfo.GetDrives();}/// <summary>///     获取本机所有进程/// </summary>/// <returns></returns>public static Process[] GetAllProcesses(){return Process.GetProcesses();}public static List<PerformanceCounter> GetAppointedCategorieCounters(PerformanceCategoryEnums.PerformanceCategoryEnum categorieEnum, bool isPrintRoot = true,bool isPrintTree = true){var result = new List<PerformanceCounter>();var categorieName = PerformanceCategoryEnums.GetCategoryNameString(categorieEnum);if (PerformanceCounterCategory.Exists(categorieName)){var category = new PerformanceCounterCategory(categorieName);PerformanceCounter[] categoryCounters;switch (category.CategoryType){case PerformanceCounterCategoryType.Unknown:categoryCounters = category.GetCounters();result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.SingleInstance:categoryCounters = category.GetCounters();result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);break;case PerformanceCounterCategoryType.MultiInstance:var categoryCounterInstanceNames = category.GetInstanceNames();if (categoryCounterInstanceNames.Length > 0){categoryCounters = category.GetCounters(categoryCounterInstanceNames[0]);result = categoryCounters.ToList();if (isPrintRoot)PrintCategoryAndCounters(category, categoryCounters, isPrintTree);}break;//default: break;
                }}return result;}/// <summary>///     获取指定磁盘可用大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveAvailableFreeSpace(DriveInfo drive){return drive.AvailableFreeSpace;}/// <summary>///     获取指定磁盘总空白大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveTotalFreeSpace(DriveInfo drive){return drive.TotalFreeSpace;}/// <summary>///     获取指定磁盘总大小/// </summary>/// <param name="drive"></param>/// <returns></returns>public static long GetDriveTotalSize(DriveInfo drive){return drive.TotalSize;}#region 获取当前使用的IP,超时时间至少1s /// <summary>///     获取当前使用的IP,超时时间至少1s/// </summary>/// <returns></returns>public static string GetLocalIP(TimeSpan timeOut, bool isBelieveTimeOutValue = false, bool recordLog = true){if (timeOut < new TimeSpan(0, 0, 1))timeOut = new TimeSpan(0, 0, 1);var isTimeOut = RunApp("route", "print", timeOut, out var result, recordLog);if (isTimeOut && !isBelieveTimeOutValue)try{var tcpClient = new TcpClient();tcpClient.Connect("www.baidu.com", 80);var ip = ((IPEndPoint) tcpClient.Client.LocalEndPoint).Address.ToString();tcpClient.Close();return ip;}catch (Exception exception){Console.WriteLine(exception);return null;}var getMatchedGroup = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");if (getMatchedGroup.Success)return getMatchedGroup.Groups[2].Value;return null;}#endregion#region 获取本机主DNS/// <summary>///     获取本机主DNS/// </summary>/// <returns></returns>public static string GetPrimaryDNS(bool recordLog = true){RunApp("nslookup", "", new TimeSpan(0, 0, 1), out var result, recordLog, true); //nslookup会超时var getMatchedGroup = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+");if (getMatchedGroup.Success)return getMatchedGroup.Value;return null;}#endregion/// <summary>///     获取指定进程最大线程数/// </summary>/// <returns></returns>public static int GetProcessMaxThreadCount(Process process){return process.Threads.Count;}/// <summary>///     获取指定进程最大线程数/// </summary>/// <returns></returns>public static int GetProcessMaxThreadCount(string processName){var maxThreadCount = -1;foreach (var process in Process.GetProcessesByName(processName))if (maxThreadCount < process.Threads.Count)maxThreadCount = process.Threads.Count;return maxThreadCount;}private static void PrintCategoryAndCounters(PerformanceCounterCategory category,PerformanceCounter[] categoryCounters, bool isPrintTree){Console.WriteLine($@"===============>{category.CategoryName}:[{categoryCounters.Length}]");if (isPrintTree)foreach (var counter in categoryCounters)Console.WriteLine($@"   ""{category.CategoryName}"", ""{counter.CounterName}""");}/// <summary>///     运行一个控制台程序并返回其输出参数。耗时至少1s/// </summary>/// <param name="filename">程序名</param>/// <param name="arguments">输入参数</param>/// <param name="result"></param>/// <param name="recordLog"></param>/// <param name="timeOutTimeSpan"></param>/// <param name="needKill"></param>/// <returns></returns>private static bool RunApp(string filename, string arguments, TimeSpan timeOutTimeSpan, out string result,bool recordLog = true, bool needKill = false){try{var stopwatch = Stopwatch.StartNew();if (recordLog)Console.WriteLine($@"{filename} {arguments}");if (timeOutTimeSpan < new TimeSpan(0, 0, 1))timeOutTimeSpan = new TimeSpan(0, 0, 1);var isTimeOut = false;var process = new Process{StartInfo ={FileName = filename,CreateNoWindow = true,Arguments = arguments,RedirectStandardOutput = true,RedirectStandardInput = true,UseShellExecute = false}};process.Start();using (var streamReader = new StreamReader(process.StandardOutput.BaseStream, Encoding.Default)){if (needKill){Thread.Sleep(200);process.Kill();}while (!process.HasExited)if (stopwatch.Elapsed > timeOutTimeSpan){process.Kill();stopwatch.Stop();isTimeOut = true;break;}result = streamReader.ReadToEnd();streamReader.Close();if (recordLog)Console.WriteLine($@"返回[{result}]耗时:[{stopwatch.Elapsed}]是否超时:{isTimeOut}");return isTimeOut;}}catch (Exception exception){result = exception.ToString();Console.WriteLine($@"出错[{result}]");return true;}}#endregion#region 获取本地/远程所有内存信息/// <summary>///     需要启动RPC服务,获取本地内存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程内存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(string remoteHostName,PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程内存信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32PhysicalMemoryInfos(IPAddress remoteHostIp,PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum eEnum = PhysicalMemoryInfoEnums.PhysicalMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PhysicalMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PhysicalMemory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PhysicalMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 获取本地/远程所有原始性能计数器类别信息/// <summary>///     需要启动RPC服务,获取本地所有原始性能计数器类别信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有原始性能计数器类别信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(string remoteHostName,PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有原始性能计数器类别信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>>GetWin32PerfRawDataPerfOsMemoryInfos(IPAddress remoteHostIp,PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum eEnum =PerfRawDataPerfOsMemoryInfoEnums.PerfRawDataPerfOsMemoryInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {PerfRawDataPerfOsMemoryInfoEnums.GetQueryString(eEnum)} FROM Win32_PerfRawData_PerfOS_Memory")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{PerfRawDataPerfOsMemoryInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 获取本地/远程所有CPU信息/// <summary>///     需要启动RPC服务,获取本地所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(string remoteHostName,ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 CPU 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessorInfos(IPAddress remoteHostIp,ProcessorInfoEnums.ProcessorInfoEnum eEnum = ProcessorInfoEnums.ProcessorInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {ProcessorInfoEnums.GetQueryString(eEnum)} FROM Win32_Processor")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessorInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 获取本地/远程所有进程信息/// <summary>///     需要启动RPC服务,获取本地所有 进程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32ProcessInfos(string processName = null, ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 进程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetRemoteWin32ProcessInfos(string remoteHostName, string processName = null,ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 进程 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetRemoteWin32ProcessInfos(IPAddress remoteHostIp, string processName = null,ProcessInfoEnums.ProcessInfoEnum eEnum = ProcessInfoEnums.ProcessInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();var selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process");if (processName != null)selectQueryString = new SelectQuery($"SELECT {ProcessInfoEnums.GetQueryString(eEnum)} FROM Win32_Process Where Name = '{processName}'");foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,selectQueryString).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{ProcessInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 获取本地/远程所有系统信息/// <summary>///     需要启动RPC服务,获取本地所有 系统 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All,bool isPrint = true){var result = new List<Dictionary<string, string>>();try{_LocalManagementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(_LocalManagementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 系统 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(string remoteHostName,OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostName}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}/// <summary>///     需要启动RPC服务,获取远程所有 系统 信息:/// </summary>/// <returns></returns>public List<Dictionary<string, string>> GetWin32OperatingSystemInfos(IPAddress remoteHostIp,OperatingSystemInfoEnums.OperatingSystemInfoEnum eEnum =OperatingSystemInfoEnums.OperatingSystemInfoEnum.All, bool isPrint = true){var result = new List<Dictionary<string, string>>();try{var managementScope = new ManagementScope($"\\\\{remoteHostIp}\\root\\cimv2");managementScope.Connect();foreach (var managementBaseObject in new ManagementObjectSearcher(managementScope,new SelectQuery($"SELECT {OperatingSystemInfoEnums.GetQueryString(eEnum)} FROM Win32_OperatingSystem")).Get()){if (isPrint)Console.WriteLine($@"<=========={managementBaseObject}===========>");var thisObjectsDictionary = new Dictionary<string, string>();foreach (var property in managementBaseObject.Properties){if (isPrint)Console.WriteLine($@"[{property.Name,40}] -> [{property.Value,-40}]//{OperatingSystemInfoEnums.GetDescriptionString(property.Name)}.");thisObjectsDictionary.Add(property.Name, property.Value.ToString());}result.Add(thisObjectsDictionary);}}catch (Exception exception){Console.WriteLine(exception);}return result;}#endregion#region 单位转换进制private const int KbDiv = 1024;private const int MbDiv = 1024 * 1024;private const int GbDiv = 1024 * 1024 * 1024;#endregion#region 单个程序Cpu使用大小/// <summary>///     获取进程一段时间内cpu平均使用率(有误差),最低500ms 内的平均值/// </summary>/// <returns></returns>public double GetProcessCpuProcessorRatio(Process process, TimeSpan interVal){if (!process.HasExited){var processorTime = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);processorTime.NextValue();if (interVal.TotalMilliseconds < 500)interVal = new TimeSpan(0, 0, 0, 0, 500);Thread.Sleep(interVal);return processorTime.NextValue() / Environment.ProcessorCount;}return 0;}/// <summary>///     获取进程一段时间内的平均cpu使用率(有误差),最低500ms 内的平均值/// </summary>/// <returns></returns>public double GetProcessCpuProcessorTime(Process process, TimeSpan interVal){if (!process.HasExited){var prevCpuTime = process.TotalProcessorTime;if (interVal.TotalMilliseconds < 500)interVal = new TimeSpan(0, 0, 0, 0, 500);Thread.Sleep(interVal);var curCpuTime = process.TotalProcessorTime;var value = (curCpuTime - prevCpuTime).TotalMilliseconds / (interVal.TotalMilliseconds - 10) /Environment.ProcessorCount * 100;return value;}return 0;}#endregion#region 单个程序内存使用大小/// <summary>///     获取关联进程分配的物理内存量,工作集(进程类)/// </summary>/// <returns></returns>public long GetProcessWorkingSet64Kb(Process process){if (!process.HasExited)return process.WorkingSet64 / KbDiv;return 0;}/// <summary>///     获取进程分配的物理内存量,公有工作集/// </summary>/// <returns></returns>public float GetProcessWorkingSetKb(Process process){if (!process.HasExited){var processWorkingSet = new PerformanceCounter("Process", "Working Set", process.ProcessName);return processWorkingSet.NextValue() / KbDiv;}return 0;}/// <summary>///     获取进程分配的物理内存量,私有工作集/// </summary>/// <returns></returns>public float GetProcessWorkingSetPrivateKb(Process process){if (!process.HasExited){var processWorkingSetPrivate =new PerformanceCounter("Process", "Working Set - Private", process.ProcessName);return processWorkingSetPrivate.NextValue() / KbDiv;}return 0;}#endregion#region 系统内存使用大小/// <summary>///     系统内存使用大小Mb/// </summary>/// <returns></returns>public long GetSystemMemoryDosageMb(){return SystemMemoryUsed / MbDiv;}/// <summary>///     系统内存使用大小Gb/// </summary>/// <returns></returns>public long GetSystemMemoryDosageGb(){return SystemMemoryUsed / GbDiv;}#endregion#region AIP声明[DllImport("IpHlpApi.dll")]public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);[DllImport("User32")]private static extern int GetWindow(int hWnd, int wCmd);[DllImport("User32")]private static extern 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 static extern int GetWindowTextLength(IntPtr hWnd);#endregion}
}

 

转载于:https://www.cnblogs.com/Chary/p/No0000112.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/253001.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

I2C总线之(一)---概述

概述&#xff1a;IC 是Inter-Integrated Circuit的缩写&#xff0c;发音为"eye-squared cee" or "eye-two-cee" , 它是一种两线接口。 IC 只是用两条双向的线&#xff0c;一条 Serial Data Line (SDA) &#xff0c;另一条Serial Clock (SCL)。 SCL&#xf…

I2C总线之(二)---时序

一、协议 1.空闲状态 I2C总线总线的SDA和SCL两条信号线同时处于高电平时&#xff0c;规定为总线的空闲状态。此时各个器件的输出级场效应管均处在截止状态&#xff0c;即释放总线&#xff0c;由两条信号线各自的上拉电阻把电平拉高。 2.起始位与停止位的定义&#xff1a; 起始信…

微信小程序设置底部导航栏目方法

微信小程序底部想要有一个漂亮的导航栏目&#xff0c;不知道怎么制作&#xff0c;于是百度找到了本篇文章&#xff0c;分享给大家。 好了 小程序的头部标题 设置好了&#xff0c;我们来说说底部导航栏是如何实现的。 我们先来看个效果图 这里&#xff0c;我们添加了三个导航图标…

HTTP协议(3)浏览器的使用之查看源码

在做CTF的Web类题目时&#xff0c;推荐使用Firefox浏览器。下面介绍一些在解题过程中关于浏览器的常用技巧。首先就是查看源码。在做Web题目时&#xff0c;经常需要查看网站源码&#xff0c;有的flag直接就藏在源码中&#xff0c;有些题目则是在源码中给出提示和线索&#xff0…

Autofac IoC容器基本使用步骤【1】

原文&#xff1a;http://www.bkjia.com/Asp_Netjc/888119.html 【原文中有一个地方报错&#xff0c;下面已修改】 一.基本步骤: 1.设计适合控制反转(IoC)的应用程序 2.给应用程序Autofac 引用. 3.注册组件. 4.创建一个Container以备后用. 5.从Container创建一个 lifetime scop…

I2C总线之(三)---以C语言理解IIC

为了加深对I2C总线的理解&#xff0c;用C语言模拟IIC总线&#xff0c;边看源代码边读波形&#xff1a; 如下图所示的写操作的时序图&#xff1a; 读时序的理解同理。对于时序不理解的朋友请参考“I2C总线之(二)---时序” 完整的程序如下&#xff1a; #include<reg51.h>…

结对编程总结

这个项目我和我的结对伙伴共花了两个月时间&#xff0c;之所以选这个项目&#xff0c;因为我们之前都学习过Python&#xff0c;也做过类似的程序&#xff0c;相比较其他项目而言&#xff0c;这个项目更合适&#xff0c;也让我们对词频统计方面的知识加深了了解。写这个程序我们…

JavaScript初学者必看“new”

2019独角兽企业重金招聘Python工程师标准>>> 译者按: 本文简单的介绍了new, 更多的是介绍原型(prototype)&#xff0c;值得一读。 原文: JavaScript For Beginners: the ‘new’ operator 译者: Fundebug 为了保证可读性&#xff0c;本文采用意译而非直译。 <di…

libGDX-wiki发布

为方便大家学习和访问&#xff0c;我将libgdx的wiki爬取到doku-wiki下&#xff0c;专门建立了以下地址。欢迎大家来共同完善。 http://wiki.v5ent.com 转载于:https://www.cnblogs.com/mignet/p/ligbdx_wiki.html

I2C读写时序

1. I2C写时序图&#xff1a; 注意&#xff1a;最后一个byte后&#xff0c;结束标志在第十个CLK上升沿之后&#xff1a; 2. I2C读时序图&#xff1a; 注意&#xff1a;restart信号格式&#xff1b;读操作结束前最后一组clk的最后一个上升沿&#xff0c;主机应发送NACK&#xff0…

软件测试工具LoadRunner中如何定义SLA?--转载

软件测试工具LoadRunner中如何定义SLA&#xff1f; 浏览&#xff1a;2242|更新&#xff1a;2017-04-09 22:50SLA 是您为负载测试场景定义的具体目标。Analysis 将这些目标与软件测试工具LoadRunner在运行过程中收集和存储的性能相关数据进行比较&#xff0c;然后确定目标的 SLA…

骁龙820和KryoCPU:异构计算与定制计算的作用 【转】

本文转载自&#xff1a;https://www.douban.com/group/topic/89037625/ Qualcomm骁龙820处理器专为提供创新用户体验的顶级移动终端而设计。为实现消费者所期望的创新&#xff0c;移动处理器必须满足日益增长的计算需求且降低功耗&#xff0c;同时还要拥有比以往更低的温度&…

亚马逊Rekognition发布针对人脸检测、分析和识别功能的多项更新

今天亚马逊Rekognition针对人脸检测、分析和识别功能推出了一系列更新。这些更新将为用户带来多项能力的改今&#xff0c;包括从图像中检测出更多人脸、执行更高精度的人脸匹配以及获得图像中的人脸得到更准确的年龄、性别和情感属性。Amazon Rekognition的客户可以从今天开始使…

华为敏捷 DevOps 实践:产品经理如何开好敏捷回顾会议

开篇小故事&#xff1a;前几年&#xff0c;一本叫《沉思录》的书在国内突然曝光度很多&#xff0c;因为前某国家领导人“摆案头&#xff0c;读百遍”。《沉思录》是古罗马皇帝马可奥勒写给自己的书&#xff0c;内容大部分是在鞍马劳顿中写的。其实有一句“我们所听到的不过只是…

Android虚拟化引擎VirtualApp探究

2019独角兽企业重金招聘Python工程师标准>>> 介绍 首先需要说明的是&#xff0c;VirtualApp并不是前些阵子滴滴开源的插件化框架VirtualApk。 VirtualApp是一个更加黑科技的东西&#xff0c;他可以创建一个虚拟空间&#xff0c;你可以在虚拟空间内任意的安装、启动和…

揭开全景相机的创业真相

&#xff08;Bubl全景相机&#xff09; 国外一开源&#xff0c;国内就自主。这在VR&#xff08;虚拟现实&#xff09;领域体现的淋漓尽致——Google的Cardborad一开源&#xff0c;国内就有数百家厂商蜂拥做了各种插手机的VR盒子。到了全景相机&#xff0c;这一幕似乎又开始重演…

一个厉害的网站

2019独角兽企业重金招聘Python工程师标准>>> dromara 发现一个网站&#xff0c;发现上面的开源项目真的都非常厉害诶。 转载于:https://my.oschina.net/miaojiangmin/blog/2934221

windwon安装macaca环境

一 安装配置java1.安装java_jdk &#xff0c;安装过程中顺带一起安装jre(1)选择【新建系统变量】--弹出“新建系统变量”对话框&#xff0c;在“变量名”文本框输入“JAVA_HOME”,在“变量值”文本框输入JDK的安装路径&#xff0c; 如“C&#xff1a;/Java/jdk1.6.0_25”(2)在“…

三星要用Exynos 9芯片打造独立VR头显

【天极网VR虚拟现实频道】近期有数据显示&#xff0c;2016年全球VR虚拟现实设备的出货量达到了630万台&#xff0c;其中三星Gear VR以451万台出货量称霸全球VR市场&#xff0c;占据高达71%的市场份额。不过三星的眼光并不局限于手机VR设备&#xff0c;这家公司正在计划推出一款…

Leetcode之二叉树(前200道)

持续更新... github链接&#xff1a;https://github.com/x2mercy/Leetcode_Solution 为什么括号200道呢&#xff01;因为准备按照200道这样的周期刷&#xff0c;每200道刷两遍&#xff0c;第一遍按难度刷&#xff0c;第二遍按类别刷&#xff01; 先整理binarytree这一类别也是因…