C# 使用win32 API 取得連接埠裝置名稱

要用Management必須先在參考中加入System.Management

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Management;
  11. namespace CSharp_Use_Win32_API_Get_PortNames
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19.  
  20. private void button1_Click(object sender, EventArgs e)
  21. {
  22. textBox1.Clear();
  23. using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
  24. {
  25. //使用ManagementObjectSearcher來查詢註冊表中的裝置名稱
  26. var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();//取得所有ManagementBaseObject並轉成List
  27. string[] PortsName = new string[ports.Count];
  28. for (int i = 0; i < ports.Count; i++)
  29. PortsName[i] = ports[i]["DeviceID"] as string + "-"
  30. + ports[i]["Caption"] as string;//取得裝置名稱與連接埠
  31. textBox1.Text = string.Join("\r\n", PortsName);
  32. }
  33. }
  34. }
  35. }

執行結果
專案下載位置:https://drive.google.com/drive/folders/0B4CEGbmc3kP9eHlrUUxWbGFsNEU?usp=sharing
檔案名稱為 CSharp_Use_Win32_API_Get_PortNames

留言

這個網誌中的熱門文章

C# 井字遊戲