C# 使用win32 API 取得連接埠裝置名稱
要用Management必須先在參考中加入System.Management
執行結果
專案下載位置:https://drive.google.com/drive/folders/0B4CEGbmc3kP9eHlrUUxWbGFsNEU?usp=sharing
檔案名稱為 CSharp_Use_Win32_API_Get_PortNames
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Management; namespace CSharp_Use_Win32_API_Get_PortNames { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { textBox1.Clear(); using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort")) { //使用ManagementObjectSearcher來查詢註冊表中的裝置名稱 var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();//取得所有ManagementBaseObject並轉成List string[] PortsName = new string[ports.Count]; for (int i = 0; i < ports.Count; i++) PortsName[i] = ports[i]["DeviceID"] as string + "-" + ports[i]["Caption"] as string;//取得裝置名稱與連接埠 textBox1.Text = string.Join("\r\n", PortsName); } } } }
執行結果
專案下載位置:https://drive.google.com/drive/folders/0B4CEGbmc3kP9eHlrUUxWbGFsNEU?usp=sharing
檔案名稱為 CSharp_Use_Win32_API_Get_PortNames
留言
張貼留言