C#使用ManagementObjectSearcher獲取本計算機CPU,硬碟,記憶體條等相關裝置資訊

斯內科發表於2020-10-14

C#獲取本作業系統顯示卡,CPU,硬碟等相關資訊,使用ManagementObjectSearcher物件來進行查詢。

新增 引用 程式集 框架 System.Management

一、新建窗體應用程式DeviceManagerDemo。重新命名Form1為FormDeviceManager。

FormDeviceManager.cs相關原始碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DeviceManagerDemo
{
    public partial class FormDeviceManager : Form
    {
        public FormDeviceManager()
        {
            InitializeComponent();
            //繫結裝置管理器
            BindAllComboBox();
            //組合框選擇索引的改變事件
            cboHardware.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
            cboOperatingSystem.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
        }

        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (cbo == null || cbo.SelectedIndex < 0) 
            {
                return;
            }
            string queryKey = cbo.SelectedValue as string;
            DisplayDeviceMessage(queryKey);      
        }

        /// <summary>
        /// 繫結硬體和作業系統 裝置管理器
        /// </summary>
        private void BindAllComboBox() 
        {
            List<Tuple<string, string>> listHandware = new List<Tuple<string, string>>();
            listHandware.Add(Tuple.Create("Win32_Processor", "CPU中央處理器"));
            listHandware.Add(Tuple.Create("Win32_PhysicalMemory", "實體記憶體條"));
            listHandware.Add(Tuple.Create("Win32_Keyboard", "鍵盤"));
            listHandware.Add(Tuple.Create("Win32_PointingDevice", "點輸入裝置,包括滑鼠。"));
            listHandware.Add(Tuple.Create("Win32_FloppyDrive", "軟盤驅動器"));
            listHandware.Add(Tuple.Create("Win32_DiskDrive", "硬碟驅動器"));
            listHandware.Add(Tuple.Create("Win32_CDROMDrive", "光碟驅動器"));
            listHandware.Add(Tuple.Create("Win32_BaseBoard", "主機板"));
            listHandware.Add(Tuple.Create("Win32_BIOS", "BIOS晶片"));
            listHandware.Add(Tuple.Create("Win32_ParallelPort", "並口"));
            listHandware.Add(Tuple.Create("Win32_SerialPort", "串列埠"));
            listHandware.Add(Tuple.Create("Win32_SerialPortConfiguration", "串列埠配置"));
            listHandware.Add(Tuple.Create("Win32_SoundDevice", "多媒體裝置,一般指音效卡"));
            listHandware.Add(Tuple.Create("Win32_SystemSlot", "主機板插槽 (ISA & PCI & AGP)"));
            listHandware.Add(Tuple.Create("Win32_USBController", "USB控制器"));
            listHandware.Add(Tuple.Create("Win32_NetworkAdapter", "網路介面卡"));
            listHandware.Add(Tuple.Create("Win32_NetworkAdapterConfiguration", "網路介面卡設定"));
            listHandware.Add(Tuple.Create("Win32_Printer", "印表機"));
            listHandware.Add(Tuple.Create("Win32_PrinterConfiguration", "印表機設定"));
            listHandware.Add(Tuple.Create("Win32_PrintJob", "印表機任務"));
            listHandware.Add(Tuple.Create("Win32_TCPIPPrinterPort", "印表機埠"));
            listHandware.Add(Tuple.Create("Win32_POTSModem", "MODEM"));
            listHandware.Add(Tuple.Create("Win32_POTSModemToSerialPort", "MODEM埠"));
            listHandware.Add(Tuple.Create("Win32_DesktopMonitor", "顯示器"));
            listHandware.Add(Tuple.Create("Win32_DisplayConfiguration", "顯示卡"));
            listHandware.Add(Tuple.Create("Win32_DisplayControllerConfiguration", "顯示卡設定"));
            listHandware.Add(Tuple.Create("Win32_VideoController", "顯示卡視訊控制器"));
            listHandware.Add(Tuple.Create("Win32_VideoSettings", "顯示卡支援的顯示模式"));
            BindCombo(listHandware, cboHardware);

            List<Tuple<string, string>> listOperatingSystem = new List<Tuple<string, string>>();
            listOperatingSystem.Add(new Tuple<string, string>("Win32_TimeZone", "時區"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_SystemDriver", "驅動程式"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_DiskPartition", "磁碟分割槽"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_LogicalDisk", "邏輯磁碟"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_LogicalDiskToPartition", "邏輯磁碟所在分割槽及始末位置"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_LogicalMemoryConfiguration", "邏輯記憶體配置"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_PageFile", "系統頁檔案資訊"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_PageFileSetting", "頁檔案設定"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_BootConfiguration", "系統啟動配置"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_ComputerSystem", "計算機資訊簡要"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_OperatingSystem", "作業系統資訊"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_StartupCommand", "系統自動啟動程式"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_Service", "系統安裝的服務"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_Group", "系統管理組"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_GroupUser", "系統組帳號"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_UserAccount", "使用者帳號"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_Process", "系統程式"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_Thread", "系統執行緒"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_Share", "共享"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_NetworkClient", "已安裝的網路客戶端"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_NetworkProtocol", "已安裝的網路協議"));
            listOperatingSystem.Add(new Tuple<string, string>("Win32_PnPEntity", "all device 【所有裝置】"));
            BindCombo(listOperatingSystem, cboOperatingSystem);
        }

        /// <summary>
        /// 資料繫結組合下拉框
        /// </summary>
        /// <param name="listSource"></param>
        /// <param name="cbo"></param>
        private void BindCombo(List<Tuple<string, string>> listSource, ComboBox cbo)
        {
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = listSource;
            cbo.DataSource = bindingSource;
            cbo.ValueMember = "Item1";
            cbo.DisplayMember = "Item2";
        }

        /// <summary>
        /// 顯示某一個裝置的相關資訊
        /// </summary>
        /// <param name="queryKey">查詢的關鍵字</param>
        private void DisplayDeviceMessage(string queryKey)
        {
            rtxtDisplay.Clear();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " + queryKey);
            ManagementObjectCollection managementObjectCollection = searcher.Get();
            DisplayMessage($"【{queryKey}】裝置資訊個數:{managementObjectCollection.Count}");
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                DisplayMessage($"管理物件的屬性個數:{managementObject.Properties.Count}");
                StringBuilder sb = new StringBuilder();
                foreach (PropertyData propertyData in managementObject.Properties)
                {
                    List<string> listQualifier = new List<string>();
                    foreach (QualifierData qualifierData in propertyData.Qualifiers)
                    {
                        listQualifier.Add($"[{qualifierData.Name}:{qualifierData.Value}]");
                    }
                    sb.Append($"    {propertyData.Name}:{propertyData.Value}--型別:【{propertyData.Type}】,限定符集合:【{string.Join(",", listQualifier)}】\n");
                }
                DisplayMessage(sb.ToString());
                DisplayMessage($"管理物件的系統屬性個數:{managementObject.SystemProperties.Count}");
                sb = new StringBuilder();
                foreach (PropertyData propertyData in managementObject.SystemProperties)
                {
                    List<string> listQualifier = new List<string>();
                    foreach (QualifierData qualifierData in propertyData.Qualifiers)
                    {
                        listQualifier.Add($"[{qualifierData.Name}:{qualifierData.Value}]");
                    }
                    sb.Append($"    {propertyData.Name}:{propertyData.Value}--型別:【{propertyData.Type}】,限定符集合:【{string.Join(",", listQualifier)}】\n");
                }
                DisplayMessage(sb.ToString());
            }
        }

        private void FormDeviceManager_Load(object sender, EventArgs e)
        {
            //新增 引用 程式集 框架 System.Management
            ComboBox_SelectedIndexChanged(cboHardware, e);            
        }

        private void DisplayMessage(string message)
        {
            this.BeginInvoke(new Action(() =>
            {
                rtxtDisplay.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}-->{message}\n");
                rtxtDisplay.ScrollToCaret();
            }));
        }
    }
}
 

二、程式執行如圖:

 

 


 

相關文章