SystemInfo.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. using Masuit.Tools.Logging;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Management;
  8. using System.Net;
  9. using System.Net.NetworkInformation;
  10. using System.Net.Sockets;
  11. using System.Runtime.InteropServices;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace Masuit.Tools.Hardware
  15. {
  16. /// <summary>
  17. /// 硬件信息,部分功能需要C++支持,仅支持Windows系统
  18. /// </summary>
  19. public static partial class SystemInfo
  20. {
  21. #region 字段
  22. private const int GwHwndfirst = 0;
  23. private const int GwHwndnext = 2;
  24. private const int GwlStyle = -16;
  25. private const int WsVisible = 268435456;
  26. private const int WsBorder = 8388608;
  27. private static readonly PerformanceCounter PcCpuLoad; //CPU计数器
  28. private static readonly PerformanceCounter MemoryCounter;
  29. private static readonly PerformanceCounter CpuCounter;
  30. private static readonly PerformanceCounter DiskReadCounter;
  31. private static readonly PerformanceCounter DiskWriteCounter;
  32. private static readonly string[] InstanceNames = new string[]{};
  33. private static readonly PerformanceCounter[] NetRecvCounters;
  34. private static readonly PerformanceCounter[] NetSentCounters;
  35. private static readonly Dictionary<string, dynamic> _cache = new();
  36. public static bool IsWinPlatform => Environment.OSVersion.Platform is PlatformID.Win32Windows
  37. or PlatformID.Win32S or PlatformID.WinCE or PlatformID.Win32NT;
  38. #endregion 字段
  39. #region 构造函数
  40. /// <summary>
  41. /// 静态构造函数
  42. /// </summary>
  43. static SystemInfo()
  44. {
  45. if (IsWinPlatform)
  46. {
  47. MemoryCounter = new PerformanceCounter();
  48. CpuCounter = new PerformanceCounter();
  49. DiskReadCounter = new PerformanceCounter();
  50. DiskWriteCounter = new PerformanceCounter();
  51. //初始化CPU计数器
  52. PcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")
  53. {
  54. MachineName = "."
  55. };
  56. PcCpuLoad.NextValue();
  57. //获得物理内存
  58. try
  59. {
  60. using var mc = new ManagementClass("Win32_ComputerSystem");
  61. using var moc = mc.GetInstances();
  62. foreach (var mo in moc)
  63. {
  64. using (mo)
  65. {
  66. if (mo["TotalPhysicalMemory"] != null)
  67. {
  68. PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
  69. }
  70. }
  71. }
  72. var cat = new PerformanceCounterCategory("Network Interface");
  73. InstanceNames = cat.GetInstanceNames();
  74. NetRecvCounters = new PerformanceCounter[InstanceNames.Length];
  75. NetSentCounters = new PerformanceCounter[InstanceNames.Length];
  76. for (int i = 0; i < InstanceNames.Length; i++)
  77. {
  78. NetRecvCounters[i] = new PerformanceCounter();
  79. NetSentCounters[i] = new PerformanceCounter();
  80. }
  81. CompactFormat = false;
  82. }
  83. catch (Exception e)
  84. {
  85. LogManager.Error(e);
  86. }
  87. }
  88. //CPU个数
  89. ProcessorCount = Environment.ProcessorCount;
  90. }
  91. #endregion 构造函数
  92. private static bool CompactFormat { get; set; }
  93. #region CPU相关
  94. /// <summary>
  95. /// 获取CPU核心数
  96. /// </summary>
  97. public static int ProcessorCount { get; }
  98. /// <summary>
  99. /// 获取CPU占用率 %
  100. /// </summary>
  101. public static float CpuLoad => PcCpuLoad?.NextValue() ?? 0;
  102. /// <summary>
  103. /// 获取当前进程的CPU使用率(至少需要0.5s)
  104. /// </summary>
  105. /// <returns></returns>
  106. public static async Task<double> GetCpuUsageForProcess()
  107. {
  108. var startTime = DateTime.UtcNow;
  109. using var p1 = Process.GetCurrentProcess();
  110. var startCpuUsage = p1.TotalProcessorTime;
  111. await Task.Delay(500);
  112. var endTime = DateTime.UtcNow;
  113. using var p2 = Process.GetCurrentProcess();
  114. var endCpuUsage = p2.TotalProcessorTime;
  115. var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
  116. var totalMsPassed = (endTime - startTime).TotalMilliseconds;
  117. return cpuUsedMs / (Environment.ProcessorCount * totalMsPassed) * 100;
  118. }
  119. /// <summary>
  120. /// WMI接口获取CPU使用率
  121. /// </summary>
  122. /// <returns></returns>
  123. public static string GetProcessorData()
  124. {
  125. var d = GetCounterValue(CpuCounter, "Processor", "% Processor Time", "_Total");
  126. return CompactFormat ? (int)d + "%" : d.ToString("F") + "%";
  127. }
  128. /// <summary>
  129. /// 获取CPU温度
  130. /// </summary>
  131. /// <returns>CPU温度</returns>
  132. public static float GetCPUTemperature()
  133. {
  134. if (IsWinPlatform is false) return 0;
  135. try
  136. {
  137. using var mos = new ManagementObjectSearcher(@"root\WMI", "select * from MSAcpi_ThermalZoneTemperature");
  138. using var moc = mos.Get();
  139. foreach (var mo in moc)
  140. {
  141. using (mo)
  142. {
  143. //这就是CPU的温度了
  144. var temp = (float.Parse(mo.Properties["CurrentTemperature"].Value.ToString()) - 2732) / 10;
  145. return (float)Math.Round(temp, 2);
  146. }
  147. }
  148. }
  149. catch (Exception)
  150. {
  151. return 0;
  152. }
  153. return 0;
  154. }
  155. /// <summary>
  156. /// 获取CPU的数量
  157. /// </summary>
  158. /// <returns>CPU的数量</returns>
  159. public static int GetCpuCount()
  160. {
  161. try
  162. {
  163. return _cache.GetOrAdd(nameof(GetCpuCount), () =>
  164. {
  165. if (IsWinPlatform is false)
  166. {
  167. int cpuCount = Environment.ProcessorCount;
  168. return cpuCount;
  169. }
  170. else
  171. {
  172. using var m = new ManagementClass("Win32_Processor");
  173. using var moc = m.GetInstances();
  174. return moc.Count;
  175. }
  176. });
  177. }
  178. catch (Exception)
  179. {
  180. return 0;
  181. }
  182. }
  183. private static readonly Lazy<List<ManagementBaseObject>> CpuObjects = new Lazy<List<ManagementBaseObject>>(() =>
  184. {
  185. using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
  186. using var moc = mos.Get();
  187. return moc.AsParallel().Cast<ManagementBaseObject>().ToList();
  188. });
  189. /// <summary>
  190. /// 获取CPU信息
  191. /// </summary>
  192. /// <returns>CPU信息</returns>
  193. public static List<CpuInfo> GetCpuInfo()
  194. {
  195. try
  196. {
  197. if (IsWinPlatform is false) return new List<CpuInfo>();
  198. return CpuObjects.Value.Select(mo => new CpuInfo
  199. {
  200. NumberOfLogicalProcessors = ProcessorCount,
  201. CurrentClockSpeed = mo.Properties["CurrentClockSpeed"].Value.ToString(),
  202. Manufacturer = mo.Properties["Manufacturer"].Value.ToString(),
  203. MaxClockSpeed = mo.Properties["MaxClockSpeed"].Value.ToString(),
  204. Type = mo.Properties["Name"].Value.ToString(),
  205. DataWidth = mo.Properties["DataWidth"].Value.ToString(),
  206. SerialNumber = mo.Properties["ProcessorId"].Value.ToString(),
  207. DeviceID = mo.Properties["DeviceID"].Value.ToString(),
  208. NumberOfCores = Convert.ToInt32(mo.Properties["NumberOfCores"].Value)
  209. }).ToList();
  210. }
  211. catch (Exception)
  212. {
  213. return new List<CpuInfo>();
  214. }
  215. }
  216. #endregion CPU相关
  217. #region 内存相关
  218. /// <summary>
  219. /// 获取可用内存
  220. /// </summary>
  221. public static long MemoryAvailable
  222. {
  223. get
  224. {
  225. if (IsWinPlatform is false) return 0;
  226. try
  227. {
  228. using var mc = new ManagementClass("Win32_OperatingSystem");
  229. using var moc = mc.GetInstances();
  230. foreach (var mo in moc)
  231. {
  232. using (mo)
  233. {
  234. if (mo["FreePhysicalMemory"] != null)
  235. {
  236. return 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
  237. }
  238. }
  239. }
  240. return 0;
  241. }
  242. catch (Exception)
  243. {
  244. return 0;
  245. }
  246. }
  247. }
  248. /// <summary>
  249. /// 获取物理内存
  250. /// </summary>
  251. public static long PhysicalMemory { get; }
  252. /// <summary>
  253. /// 获取内存信息
  254. /// </summary>
  255. /// <returns>内存信息</returns>
  256. public static RamInfo GetRamInfo()
  257. {
  258. return new RamInfo
  259. {
  260. MemoryAvailable = GetFreePhysicalMemory(),
  261. PhysicalMemory = GetTotalPhysicalMemory(),
  262. TotalPageFile = GetTotalVirtualMemory(),
  263. AvailablePageFile = GetTotalVirtualMemory() - GetUsedVirtualMemory(),
  264. AvailableVirtual = 1 - GetUsageVirtualMemory(),
  265. TotalVirtual = 1 - GetUsedPhysicalMemory()
  266. };
  267. }
  268. /// <summary>
  269. /// 获取虚拟内存使用率详情
  270. /// </summary>
  271. /// <returns></returns>
  272. public static string GetMemoryVData()
  273. {
  274. float d = GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  275. var str = d.ToString("F") + "% (";
  276. d = GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  277. str += FormatBytes(d) + " / ";
  278. d = GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  279. return str + FormatBytes(d) + ") ";
  280. }
  281. /// <summary>
  282. /// 获取虚拟内存使用率
  283. /// </summary>
  284. /// <returns></returns>
  285. public static float GetUsageVirtualMemory()
  286. {
  287. return GetCounterValue(MemoryCounter, "Memory", "% Committed Bytes In Use", null);
  288. }
  289. /// <summary>
  290. /// 获取虚拟内存已用大小
  291. /// </summary>
  292. /// <returns></returns>
  293. public static float GetUsedVirtualMemory()
  294. {
  295. return GetCounterValue(MemoryCounter, "Memory", "Committed Bytes", null);
  296. }
  297. /// <summary>
  298. /// 获取虚拟内存总大小
  299. /// </summary>
  300. /// <returns></returns>
  301. public static float GetTotalVirtualMemory()
  302. {
  303. return GetCounterValue(MemoryCounter, "Memory", "Commit Limit", null);
  304. }
  305. /// <summary>
  306. /// 获取物理内存使用率详情描述
  307. /// </summary>
  308. /// <returns></returns>
  309. public static string GetMemoryPData()
  310. {
  311. string s = QueryComputerSystem("totalphysicalmemory");
  312. if (string.IsNullOrEmpty(s)) return "";
  313. float totalphysicalmemory = Convert.ToSingle(s);
  314. float d = GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  315. d = totalphysicalmemory - d;
  316. s = CompactFormat ? "%" : "% (" + FormatBytes(d) + " / " + FormatBytes(totalphysicalmemory) + ")";
  317. d /= totalphysicalmemory;
  318. d *= 100;
  319. return CompactFormat ? (int)d + s : d.ToString("F") + s;
  320. }
  321. /// <summary>
  322. /// 获取物理内存总数,单位B
  323. /// </summary>
  324. /// <returns></returns>
  325. public static float GetTotalPhysicalMemory()
  326. {
  327. return _cache.GetOrAdd(nameof(GetTotalPhysicalMemory), () =>
  328. {
  329. var s = QueryComputerSystem("totalphysicalmemory");
  330. return s.TryConvertTo<float>();
  331. });
  332. }
  333. /// <summary>
  334. /// 获取空闲的物理内存数,单位B
  335. /// </summary>
  336. /// <returns></returns>
  337. public static float GetFreePhysicalMemory()
  338. {
  339. return GetCounterValue(MemoryCounter, "Memory", "Available Bytes", null);
  340. }
  341. /// <summary>
  342. /// 获取已经使用了的物理内存数,单位B
  343. /// </summary>
  344. /// <returns></returns>
  345. public static float GetUsedPhysicalMemory()
  346. {
  347. return GetTotalPhysicalMemory() - GetFreePhysicalMemory();
  348. }
  349. #endregion 内存相关
  350. #region 硬盘相关
  351. /// <summary>
  352. /// 获取硬盘的读写速率
  353. /// </summary>
  354. /// <param name="dd">读或写</param>
  355. /// <returns></returns>
  356. public static float GetDiskData(DiskData dd) => dd == DiskData.Read ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") : dd == DiskData.Write ? GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : dd == DiskData.ReadAndWrite ? GetCounterValue(DiskReadCounter, "PhysicalDisk", "Disk Read Bytes/sec", "_Total") + GetCounterValue(DiskWriteCounter, "PhysicalDisk", "Disk Write Bytes/sec", "_Total") : 0;
  357. private static readonly List<DiskInfo> DiskInfos = new();
  358. /// <summary>
  359. /// 获取磁盘可用空间
  360. /// </summary>
  361. /// <returns></returns>
  362. public static List<DiskInfo> GetDiskInfo()
  363. {
  364. try
  365. {
  366. if (IsWinPlatform == false || DiskInfos.Count > 0)
  367. {
  368. return DiskInfos;
  369. }
  370. using var mc = new ManagementClass("Win32_DiskDrive");
  371. using var moc = mc.GetInstances();
  372. foreach (var mo in moc)
  373. {
  374. using (mo)
  375. {
  376. DiskInfos.Add(new DiskInfo()
  377. {
  378. Total = float.Parse(mo["Size"].ToString()),
  379. Model = mo["Model"].ToString(),
  380. SerialNumber = mo["SerialNumber"].ToString(),
  381. });
  382. }
  383. }
  384. return DiskInfos;
  385. }
  386. catch (Exception)
  387. {
  388. return new List<DiskInfo>();
  389. }
  390. }
  391. #endregion 硬盘相关
  392. #region 网络相关
  393. /// <summary>
  394. /// 获取网络的传输速率
  395. /// </summary>
  396. /// <param name="nd">上传或下载</param>
  397. /// <returns></returns>
  398. public static float GetNetData(NetData nd)
  399. {
  400. if (InstanceNames is {Length: 0}) return 0;
  401. float d = 0;
  402. for (int i = 0; i < InstanceNames.Length; i++)
  403. {
  404. float receied = GetCounterValue(NetRecvCounters[i], "Network Interface", "Bytes Received/sec", InstanceNames[i]);
  405. float send = GetCounterValue(NetSentCounters[i], "Network Interface", "Bytes Sent/sec", InstanceNames[i]);
  406. switch (nd)
  407. {
  408. case NetData.Received:
  409. d += receied;
  410. break;
  411. case NetData.Sent:
  412. d += send;
  413. break;
  414. case NetData.ReceivedAndSent:
  415. d += receied + send;
  416. break;
  417. default:
  418. d += 0;
  419. break;
  420. }
  421. }
  422. return d;
  423. }
  424. /// <summary>
  425. /// 获取网卡硬件地址
  426. /// </summary>
  427. /// <returns></returns>
  428. public static IList<string> GetMacAddress()
  429. {
  430. //获取网卡硬件地址
  431. try
  432. {
  433. if (IsWinPlatform is false) return new List<string>();
  434. return _cache.GetOrAdd(nameof(GetMacAddress), () =>
  435. {
  436. IList<string> list = new List<string>();
  437. using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  438. using var moc = mc.GetInstances();
  439. foreach (var mo in moc)
  440. {
  441. using (mo)
  442. {
  443. if ((bool)mo["IPEnabled"])
  444. {
  445. list.Add(mo["MacAddress"].ToString());
  446. }
  447. }
  448. }
  449. return list;
  450. });
  451. }
  452. catch (Exception)
  453. {
  454. return new List<string>();
  455. }
  456. }
  457. /// <summary>
  458. /// 获取当前使用的IP
  459. /// </summary>
  460. /// <returns></returns>
  461. public static IPAddress GetLocalUsedIP()
  462. {
  463. return GetLocalUsedIP(AddressFamily.InterNetwork);
  464. }
  465. /// <summary>
  466. /// 获取IP地址WMI
  467. /// </summary>
  468. /// <returns></returns>
  469. public static string GetIPAddressWMI()
  470. {
  471. try
  472. {
  473. if (IsWinPlatform is false) return "";
  474. return _cache.GetOrAdd(nameof(GetIPAddressWMI), () =>
  475. {
  476. using var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  477. using var moc = mc.GetInstances();
  478. foreach (var mo in moc)
  479. {
  480. if ((bool)mo["IPEnabled"])
  481. {
  482. return ((string[])mo.Properties["IpAddress"].Value)[0];
  483. }
  484. }
  485. return "";
  486. });
  487. }
  488. catch (Exception e)
  489. {
  490. Console.WriteLine(e.Message);
  491. }
  492. return "";
  493. }
  494. /// <summary>
  495. /// 获取当前使用的IP
  496. /// </summary>
  497. /// <returns></returns>
  498. public static IPAddress GetLocalUsedIP(AddressFamily family)
  499. {
  500. if (IsWinPlatform is false) return default;
  501. return NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed).Select(t => t.GetIPProperties()).Where(p => p.DhcpServerAddresses.Count > 0).SelectMany(p => p.UnicastAddresses).Select(p => p.Address).FirstOrDefault(p => !(p.IsIPv6Teredo || p.IsIPv6LinkLocal || p.IsIPv6Multicast || p.IsIPv6SiteLocal) && p.AddressFamily == family);
  502. }
  503. /// <summary>
  504. /// 获取本机所有的ip地址
  505. /// </summary>
  506. /// <returns></returns>
  507. public static List<UnicastIPAddressInformation> GetLocalIPs()
  508. {
  509. var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(c => c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up).OrderByDescending(c => c.Speed); //所有网卡信息
  510. return interfaces.SelectMany(n => n.GetIPProperties().UnicastAddresses).ToList();
  511. }
  512. /// <summary>
  513. /// 获取网卡地址
  514. /// </summary>
  515. /// <returns></returns>
  516. public static string GetNetworkCardAddress()
  517. {
  518. try
  519. {
  520. if (IsWinPlatform is false) return "";
  521. return _cache.GetOrAdd(nameof(GetNetworkCardAddress), () =>
  522. {
  523. using var mos = new ManagementObjectSearcher("select * from Win32_NetworkAdapter where ((MACAddress Is Not NULL) and (Manufacturer <> 'Microsoft'))");
  524. using var moc = mos.Get();
  525. foreach (var mo in moc)
  526. {
  527. return mo["MACAddress"].ToString().Trim();
  528. }
  529. return "";
  530. });
  531. }
  532. catch (Exception e)
  533. {
  534. Console.WriteLine(e.Message);
  535. }
  536. return "";
  537. }
  538. #endregion 网络相关
  539. #region 系统相关
  540. /// <summary>
  541. /// 获取计算机开机时间
  542. /// </summary>
  543. /// <returns>datetime</returns>
  544. public static DateTime BootTime()
  545. {
  546. if (IsWinPlatform is false) return default;
  547. var query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
  548. using var searcher = new ManagementObjectSearcher(query);
  549. using var moc = searcher.Get();
  550. foreach (var mo in moc)
  551. {
  552. using (mo)
  553. {
  554. return ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
  555. }
  556. }
  557. return DateTime.Now - TimeSpan.FromMilliseconds(Environment.TickCount & int.MaxValue);
  558. }
  559. /// <summary>
  560. /// 查询计算机系统信息
  561. /// </summary>
  562. /// <param name="type">类型名</param>
  563. /// <returns></returns>
  564. public static string QueryComputerSystem(string type)
  565. {
  566. try
  567. {
  568. if (IsWinPlatform is false) return string.Empty;
  569. var mos = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
  570. using var moc = mos.Get();
  571. foreach (var mo in moc)
  572. {
  573. using (mo)
  574. {
  575. return mo[type].ToString();
  576. }
  577. }
  578. }
  579. catch (Exception e)
  580. {
  581. return "未能获取到当前计算机系统信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。异常信息:" + e.Message;
  582. }
  583. return string.Empty;
  584. }
  585. /// <summary>
  586. /// 查找所有应用程序标题
  587. /// </summary>
  588. /// <param name="handle">应用程序标题范型</param>
  589. /// <returns>所有应用程序集合</returns>
  590. public static ArrayList FindAllApps(int handle)
  591. {
  592. if (IsWinPlatform is false) return default;
  593. var apps = new ArrayList();
  594. int hwCurr = GetWindow(handle, GwHwndfirst);
  595. while (hwCurr > 0)
  596. {
  597. int IsTask = WsVisible | WsBorder;
  598. int lngStyle = GetWindowLongA(hwCurr, GwlStyle);
  599. bool taskWindow = (lngStyle & IsTask) == IsTask;
  600. if (taskWindow)
  601. {
  602. int length = GetWindowTextLength(new IntPtr(hwCurr));
  603. StringBuilder sb = new StringBuilder(2 * length + 1);
  604. GetWindowText(hwCurr, sb, sb.Capacity);
  605. string strTitle = sb.ToString();
  606. if (!string.IsNullOrEmpty(strTitle))
  607. {
  608. apps.Add(strTitle);
  609. }
  610. }
  611. hwCurr = GetWindow(hwCurr, GwHwndnext);
  612. }
  613. return apps;
  614. }
  615. /// <summary>
  616. /// 操作系统类型
  617. /// </summary>
  618. /// <returns></returns>
  619. public static string GetSystemType()
  620. {
  621. try
  622. {
  623. return _cache.GetOrAdd(nameof(GetSystemType), () =>
  624. {
  625. if (IsWinPlatform is false)
  626. {
  627. return Environment.OSVersion.Platform.ToString();
  628. }
  629. else
  630. {
  631. using var mc = new ManagementClass("Win32_ComputerSystem");
  632. using var moc = mc.GetInstances();
  633. foreach (var mo in moc)
  634. {
  635. return mo["SystemType"].ToString().Trim();
  636. }
  637. return "";
  638. }
  639. });
  640. }
  641. catch (Exception e)
  642. {
  643. Console.WriteLine(e.Message);
  644. }
  645. return "";
  646. }
  647. #endregion 系统相关
  648. #region 主板相关
  649. /// <summary>
  650. /// 获取主板序列号
  651. /// </summary>
  652. /// <returns></returns>
  653. public static string GetBiosSerialNumber()
  654. {
  655. try
  656. {
  657. if (IsWinPlatform is false) return "";
  658. return _cache.GetOrAdd(nameof(GetBiosSerialNumber), () =>
  659. {
  660. using var searcher = new ManagementObjectSearcher("select * from Win32_BIOS");
  661. using var mos = searcher.Get();
  662. foreach (var mo in mos)
  663. {
  664. return mo["SerialNumber"].ToString().Trim();
  665. }
  666. return "";
  667. });
  668. }
  669. catch (Exception e)
  670. {
  671. Console.WriteLine(e.Message);
  672. }
  673. return "";
  674. }
  675. /// <summary>
  676. /// 主板编号
  677. /// </summary>
  678. /// <returns></returns>
  679. public static BiosInfo GetBiosInfo()
  680. {
  681. if (IsWinPlatform is false) return new BiosInfo();
  682. return _cache.GetOrAdd(nameof(GetBiosInfo), () =>
  683. {
  684. using var searcher = new ManagementObjectSearcher("select * from Win32_BaseBoard");
  685. using var mos = searcher.Get();
  686. foreach (var mo in mos)
  687. {
  688. return new BiosInfo
  689. {
  690. Manufacturer = mo.GetPropertyValue("Manufacturer").ToString(),
  691. ID = mo["SerialNumber"].ToString(),
  692. Model = mo["Product"].ToString(),
  693. SerialNumber = GetBiosSerialNumber()
  694. };
  695. }
  696. return new BiosInfo();
  697. });
  698. }
  699. #endregion 主板相关
  700. #region 公共函数
  701. /// <summary>
  702. /// 将速度值格式化成字节单位
  703. /// </summary>
  704. /// <param name="bytes"></param>
  705. /// <returns></returns>
  706. public static string FormatBytes(this double bytes)
  707. {
  708. int unit = 0;
  709. while (bytes > 1024)
  710. {
  711. bytes /= 1024;
  712. ++unit;
  713. }
  714. string s = CompactFormat ? ((int)bytes).ToString() : bytes.ToString("F") + " ";
  715. return s + (Unit)unit;
  716. }
  717. private static float GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName)
  718. {
  719. if (IsWinPlatform is false) return 0;
  720. pc.CategoryName = categoryName;
  721. pc.CounterName = counterName;
  722. pc.InstanceName = instanceName;
  723. return pc.NextValue();
  724. }
  725. #endregion 公共函数
  726. #region Win32API声明
  727. #pragma warning disable 1591
  728. [DllImport("User32")]
  729. public static extern int GetWindow(int hWnd, int wCmd);
  730. [DllImport("User32")]
  731. public static extern int GetWindowLongA(int hWnd, int wIndx);
  732. [DllImport("user32.dll")]
  733. public static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
  734. [DllImport("user32", CharSet = CharSet.Auto)]
  735. public static extern int GetWindowTextLength(IntPtr hWnd);
  736. #pragma warning restore 1591
  737. #endregion Win32API声明
  738. }
  739. }