// 电脑信息(硬件配置一键查看) // 数据源:Windows WMI(System.Management,框架自带),离线、免费、不装驱动不上传。 // 说明:市面上同类工具多是全家桶(弹窗广告/常驻后台),这里做纯绿色单文件版。 // 全部查询丢线程池执行,界面先出后填充;自测断言 WMI 真实数据。 using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Management; namespace GtPcInfo { /* ───────────── 核心:WMI 查询 ───────────── */ public static class PcOps { /* 通用查询:返回每行一个字典(键=属性名,值=字符串) */ public static List> Query(string wmiClass, params string[] props) { List> rows = new List>(); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher( "SELECT " + string.Join(",", props) + " FROM " + wmiClass)) { foreach (ManagementObject mo in searcher.Get()) { Dictionary row = new Dictionary(); foreach (string p in props) { object v = mo[p]; row[p] = v == null ? "" : v.ToString().Trim(); } rows.Add(row); } } return rows; } static string FmtBytes(object v) { ulong n; if (v == null || !ulong.TryParse(v.ToString(), out n)) return ""; return (n / (1024.0 * 1024.0 * 1024.0)).ToString("0.#") + " GB"; } /* 人类友好的单值查询 */ public static string QuerySingle(string wmiClass, string prop) { List> rows = Query(wmiClass, new string[] { prop }); return rows.Count > 0 ? rows[0][prop] : ""; } /* 汇总:返回分区标题 → 行列表(键: 值) */ public static Dictionary>> Collect() { return Task.Run(() => CollectCore()).GetAwaiter().GetResult(); } static Dictionary>> CollectCore() { Dictionary>> sections = new Dictionary>>(); // ── 操作系统 ── List> os = new List>(); try { List> rows = Query("Win32_OperatingSystem", "Caption", "Version", "OSArchitecture", "LastBootUpTime"); if (rows.Count > 0) { var r = rows[0]; os.Add(KV("系统", r["Caption"])); os.Add(KV("版本", r["Version"] + (r["OSArchitecture"].Length > 0 ? " " + r["OSArchitecture"] : ""))); string boot = ParseWmiDate(r["LastBootUpTime"]); if (boot.Length > 0) os.Add(KV("上次开机", boot)); } } catch (Exception ex) { os.Add(KV("系统", "查询失败:" + ex.Message)); } sections["操作系统"] = os; // ── CPU ── List> cpu = new List>(); try { List> rows = Query("Win32_Processor", "Name", "NumberOfCores", "NumberOfLogicalProcessors", "MaxClockSpeed"); foreach (var r in rows) { string name = CleanCpuName(r["Name"]); cpu.Add(KV("处理器", name)); cpu.Add(KV("核心/线程", r["NumberOfCores"] + " 核 " + r["NumberOfLogicalProcessors"] + " 线程")); int mhz; if (int.TryParse(r["MaxClockSpeed"], out mhz)) cpu.Add(KV("标称频率", (mhz / 1000.0).ToString("0.##") + " GHz")); } } catch (Exception ex) { cpu.Add(KV("处理器", "查询失败:" + ex.Message)); } sections["处理器"] = cpu; // ── 内存(每条一行)── List> mem = new List>(); try { List> rows = Query("Win32_PhysicalMemory", "Capacity", "Speed", "ConfiguredClockSpeed", "Manufacturer", "DeviceLocator"); double total = 0; foreach (var r in rows) { ulong cap; ulong.TryParse(r["Capacity"], out cap); total += cap; string gb = cap > 0 ? (cap / (1024.0 * 1024.0 * 1024.0)).ToString("0.#") + " GB" : "?"; string speed = r["ConfiguredClockSpeed"].Length > 0 ? r["ConfiguredClockSpeed"] : r["Speed"]; string slot = r["DeviceLocator"]; mem.Add(KV(string.IsNullOrEmpty(slot) ? "内存条" : slot, gb + (speed.Length > 0 ? " " + speed + " MHz" : "") + (r["Manufacturer"].Length > 0 ? " " + r["Manufacturer"] : ""))); } if (total > 0) mem.Insert(0, KV("总容量", (total / (1024.0 * 1024.0 * 1024.0)).ToString("0.#") + " GB")); if (rows.Count == 0) mem.Add(KV("内存条", "未检测到(可能是虚拟机)")); } catch (Exception ex) { mem.Add(KV("内存", "查询失败:" + ex.Message)); } sections["内存"] = mem; // ── 显卡 ── List> gpu = new List>(); try { List> rows = Query("Win32_VideoController", "Name", "AdapterRAM", "CurrentHorizontalResolution", "CurrentVerticalResolution", "CurrentRefreshRate", "DriverVersion"); foreach (var r in rows) { gpu.Add(KV("显卡", r["Name"])); string res = ""; int w, h, hz; if (int.TryParse(r["CurrentHorizontalResolution"], out w) && int.TryParse(r["CurrentVerticalResolution"], out h)) { res = w + " × " + h; if (int.TryParse(r["CurrentRefreshRate"], out hz) && hz > 0) res += " @ " + hz + "Hz"; } if (res.Length > 0) gpu.Add(KV("当前输出", res)); if (r["DriverVersion"].Length > 0) gpu.Add(KV("驱动版本", r["DriverVersion"])); } } catch (Exception ex) { gpu.Add(KV("显卡", "查询失败:" + ex.Message)); } sections["显卡"] = gpu; // ── 硬盘 ── List> disk = new List>(); try { List> rows = Query("Win32_DiskDrive", "Model", "Size", "InterfaceType"); int idx = 1; foreach (var r in rows) { string size = FmtBytes(r["Size"]); disk.Add(KV("硬盘 " + idx, r["Model"] + (size.Length > 0 ? " " + size : "") + (r["InterfaceType"].Length > 0 ? " " + r["InterfaceType"] : ""))); idx++; } } catch (Exception ex) { disk.Add(KV("硬盘", "查询失败:" + ex.Message)); } sections["硬盘"] = disk; // ── 主板 / BIOS ── List> board = new List>(); try { List> rows = Query("Win32_BaseBoard", "Manufacturer", "Product"); if (rows.Count > 0) board.Add(KV("主板", (rows[0]["Manufacturer"] + " " + rows[0]["Product"]).Trim())); List> bios = Query("Win32_BIOS", "Manufacturer", "SMBIOSBIOSVersion", "ReleaseDate"); if (bios.Count > 0) { board.Add(KV("BIOS", (bios[0]["Manufacturer"] + " " + bios[0]["SMBIOSBIOSVersion"]).Trim())); string rel = ParseWmiDate(bios[0]["ReleaseDate"]); if (rel.Length > 0) board.Add(KV("BIOS 日期", rel)); } } catch (Exception ex) { board.Add(KV("主板", "查询失败:" + ex.Message)); } sections["主板"] = board; // ── 声卡 / 网卡 ── List> misc = new List>(); try { List> snd = Query("Win32_SoundDevice", "Name"); foreach (var r in snd) misc.Add(KV("声卡", r["Name"])); List> net = Query("Win32_NetworkAdapter", "Name", "PhysicalAdapter", "NetEnabled"); foreach (var r in net) { if (r["PhysicalAdapter"] == "True") misc.Add(KV(r["NetEnabled"] == "True" ? "网卡(已连)" : "网卡", r["Name"])); } List> mon = Query("Win32_DesktopMonitor", "Name"); foreach (var r in mon) if (r["Name"].Length > 0 && r["Name"] != "Default Monitor") misc.Add(KV("显示器", r["Name"])); } catch (Exception ex) { misc.Add(KV("其他", "查询失败:" + ex.Message)); } sections["声卡/网卡"] = misc; return sections; } static KeyValuePair KV(string k, string v) { return new KeyValuePair(k, v); } /* WMI 日期(yyyymmddHHMMSS…)→ yyyy-MM-dd HH:mm */ public static string ParseWmiDate(string s) { if (string.IsNullOrEmpty(s) || s.Length < 14) return ""; // DMTF 格式可能带时区后缀和 .xxxxxx string digits = ""; foreach (char c in s) { if (char.IsDigit(c)) digits += c; else if (c == '.' || c == '+' || c == '-') break; } if (digits.Length < 14) return ""; return digits.Substring(0, 4) + "-" + digits.Substring(4, 2) + "-" + digits.Substring(6, 2) + " " + digits.Substring(8, 2) + ":" + digits.Substring(10, 2); } /* CPU 名清理:去多余空格与 (R) (TM) */ public static string CleanCpuName(string name) { if (string.IsNullOrEmpty(name)) return ""; string t = name.Replace("(R)", "").Replace("(TM)", "").Replace("(r)", "").Replace("(tm)", ""); while (t.Contains(" ")) t = t.Replace(" ", " "); return t.Trim(); } /* 汇总 → 纯文本(导出/复制用) */ public static string ToText(Dictionary>> sections) { StringBuilder sb = new StringBuilder(); sb.AppendLine("电脑信息 — " + DateTime.Now.ToString("yyyy-MM-dd HH:mm")); sb.AppendLine(new string('=', 16)); foreach (var sec in sections) { sb.AppendLine("【" + sec.Key + "】"); foreach (var kv in sec.Value) sb.AppendLine(" " + kv.Key + ": " + kv.Value); sb.AppendLine(); } return sb.ToString(); } } /* ───────────── 界面 ───────────── */ public class PcInfoForm : Form { public bool headless; TextBox _body; Button _copy, _export, _refresh; Label _status; public PcInfoForm() { Text = "电脑信息 — 绿色工具箱"; Font = new System.Drawing.Font("Microsoft YaHei UI", 9F); Size = new System.Drawing.Size(640, 620); StartPosition = FormStartPosition.CenterScreen; _body = new TextBox(); _body.Multiline = true; _body.ReadOnly = true; _body.ScrollBars = ScrollBars.Vertical; _body.WordWrap = false; _body.SetBounds(12, 12, 600, 500); _body.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; Controls.Add(_body); _refresh = new Button(); _refresh.Text = "重新检测"; _refresh.SetBounds(12, 524, 100, 30); _refresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; _refresh.Click += delegate { LoadInfo(); }; Controls.Add(_refresh); _copy = new Button(); _copy.Text = "复制全部"; _copy.SetBounds(124, 524, 100, 30); _copy.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; _copy.Click += delegate { try { Clipboard.SetText(_body.Text); _status.Text = "已复制到剪贴板"; } catch { _status.Text = "复制失败"; } }; Controls.Add(_copy); _export = new Button(); _export.Text = "导出 TXT"; _export.SetBounds(236, 524, 100, 30); _export.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; _export.Click += delegate { Export(); }; Controls.Add(_export); _status = new Label(); _status.Text = ""; _status.SetBounds(350, 530, 260, 22); _status.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; Controls.Add(_status); if (!headless) LoadInfo(); } void LoadInfo() { _refresh.Enabled = false; _status.Text = "正在检测…"; ThreadPool.QueueUserWorkItem(delegate { string text; try { text = PcOps.ToText(PcOps.Collect()); } catch (Exception ex) { text = "检测失败:" + ex.Message; } BeginInvoke((MethodInvoker)delegate { _body.Text = text; _refresh.Enabled = true; _status.Text = "检测完成"; }); }); } void Export() { using (SaveFileDialog sd = new SaveFileDialog()) { sd.Filter = "文本文件|*.txt"; sd.FileName = "电脑信息_" + Environment.MachineName + "_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt"; if (sd.ShowDialog(this) == DialogResult.OK) { File.WriteAllText(sd.FileName, _body.Text, new UTF8Encoding(false)); _status.Text = "已导出:" + Path.GetFileName(sd.FileName); try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + sd.FileName + "\""); } catch { } } } } protected override void SetVisibleCore(bool value) { base.SetVisibleCore(headless ? false : value); } } /* ───────────── 自测 ───────────── */ public static class PcInfoSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } static void CheckTrue(string name, bool cond) { Check(name, cond, true); } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("电脑信息 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-pcinfo-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); try { Console.OutputEncoding = Encoding.UTF8; } catch { } // 1. WMI 基础查询真实数据 var osRows = PcOps.Query("Win32_OperatingSystem", "Caption"); CheckTrue("OS 查询有结果", osRows.Count > 0 && osRows[0]["Caption"].Length > 0); var cpuRows = PcOps.Query("Win32_Processor", "Name"); CheckTrue("CPU 查询有结果", cpuRows.Count > 0 && cpuRows[0]["Name"].Length > 0); var memRows = PcOps.Query("Win32_PhysicalMemory", "Capacity"); CheckTrue("内存查询有结果", memRows.Count >= 1); var gpuRows = PcOps.Query("Win32_VideoController", "Name"); CheckTrue("显卡查询有结果", gpuRows.Count >= 1); var diskRows = PcOps.Query("Win32_DiskDrive", "Model"); CheckTrue("硬盘查询有结果", diskRows.Count >= 1); // 2. 汇总 var sections = PcOps.Collect(); CheckTrue("汇总含操作系统区", sections.ContainsKey("操作系统") && sections["操作系统"].Count > 0); CheckTrue("汇总含处理器区", sections.ContainsKey("处理器") && sections["处理器"].Count > 0); CheckTrue("汇总含内存区", sections.ContainsKey("内存") && sections["内存"].Count > 0); CheckTrue("汇总含显卡区", sections.ContainsKey("显卡") && sections["显卡"].Count > 0); CheckTrue("汇总含硬盘区", sections.ContainsKey("硬盘") && sections["硬盘"].Count > 0); CheckTrue("汇总含主板区", sections.ContainsKey("主板") && sections["主板"].Count > 0); // 3. 文本格式 string text = PcOps.ToText(sections); CheckTrue("文本含标题", text.Contains("电脑信息")); CheckTrue("文本含 CPU 行", text.Contains("处理器")); CheckTrue("文本含内存行", text.Contains("内存")); CheckTrue("文本 GB 单位", text.Contains("GB")); // 4. 日期解析 Check("WMI 日期解析", PcOps.ParseWmiDate("20261024093000.000000+480"), "2026-10-24 09:30"); Check("WMI 日期空值", PcOps.ParseWmiDate(""), ""); Check("WMI 日期过短", PcOps.ParseWmiDate("2026"), ""); // 5. CPU 名清理 Check("CPU 名清理", PcOps.CleanCpuName("Intel(R) Core(TM) i7-10870H CPU @ 2.20GHz"), "Intel Core i7-10870H CPU @ 2.20GHz"); Check("CPU 名空值", PcOps.CleanCpuName(""), ""); // 6. 容量格式 CheckTrue("单值查询非空", PcOps.QuerySingle("Win32_OperatingSystem", "Caption").Length > 0); // 7. 导出 txt string outTxt = Path.Combine(baseDir, "pcinfo.txt"); System.IO.File.WriteAllText(outTxt, text, new UTF8Encoding(false)); CheckTrue("导出文件存在且非空", System.IO.File.Exists(outTxt) && new FileInfo(outTxt).Length > 200); // 8. Form 层 PcInfoForm form = new PcInfoForm(); form.headless = true; CheckTrue("窗体控件就绪", form.Controls.Count >= 5); } catch (Exception ex) { _lines.Add("异常: " + ex.GetType().Name + ": " + ex.Message); _fail++; } _lines.Add("结果: " + _pass + " 通过, " + _fail + " 失败"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-pcinfo.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } /* ───────────── 入口 ───────────── */ static class Program { [STAThread] static int Main(string[] args) { if (args.Length >= 1 && args[0] == "--selftest") return PcInfoSelfTest.Run(args.Length >= 2 ? args[1] : null); using (Mutex mutex = new Mutex(true, "GT-PCINFO-单实例")) { if (!mutex.WaitOne(0, false)) return 0; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PcInfoForm()); } return 0; } } }