/*
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
*/
using System;
using System.Windows.Forms;
using System.Management;//手动引用 System.Management.dll
namespace enumSerial
{
public partial class Form1 : Form
{
private ComboBox comboBox2;
private ComboBox comboBox1;
public Form1()
{
InitializeComponent();
GetComList();
GetComNum();
}
private void GetComList()
{//using System.Management; //手动引用 System.Management.dll
try
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
{
var hardInfos = searcher.Get();
int index = 1;
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties["Name"].Value != null && hardInfo.Properties["Name"].Value.ToString().Contains("(COM"))
{
String strComName = hardInfo.Properties["Name"].Value.ToString();
comboBox1.Items.Add(index + ":" + strComName);
index += 1;
}
}
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedIndex = 0;
}
}
catch
{
}
}
private void GetComNum()
{
foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox2.Items.Add(com);
}
comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox2.SelectedIndex = 0;
}
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(31, 51);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(478, 20);
this.comboBox1.TabIndex = 0;
//
// comboBox2
//
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point(31, 151);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(478, 20);
this.comboBox2.TabIndex = 1;
//
// Form1
//
this.ClientSize = new System.Drawing.Size(616, 481);
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.comboBox1);
this.Name = "枚举可用串口号.";
this.ResumeLayout(false);
}
}
}
C#枚举串口号
最新推荐文章于 2024-06-01 15:17:34 发布