命名空间
using System.IO.Ports; //Serial
using System.IO;
using System.Runtime.InteropServices; //Struct
using System.Management; //ManagementObjectSearchers
需要手动添加服务
private static string TWE_LITE_ID = "FTDIBUS\\VID_0403+PID_6001";//FTDIBUS\\VID_0403
public enum HardwareEnum
{
//Hardware
Win32_Processor, // CPU
Win32_PhysicalMemory, // Physical memory
Win32_Keyboard, // Keyboard
Win32_PointingDevice, // Point the input device, including the mouse.
Win32_FloppyDrive, // Floppy disk drive
Win32_DiskDrive, // Hard disk drive
Win32_CDROMDrive, // CD-ROM drive
Win32_BaseBoard, // Motherboard
Win32_BIOS, // BIOS
Win32_ParallelPort, // Parallel port
Win32_SerialPort, // Serial port
Win32_SerialPortConfiguration, // Serial configuration
Win32_SoundDevice, // Multimedia equipment, generally refers to the sound card.
Win32_SystemSlot, // ISA & PCI & AGP
Win32_USBController, // USB controller
Win32_NetworkAdapter, // Network adapter
Win32_NetworkAdapterConfiguration, // Network adapter settings
Win32_Printer, // Printer
Win32_PrinterConfiguration, // Printer settings
Win32_PrintJob, // Printer task
Win32_TCPIPPrinterPort, // Printer port
Win32_POTSModem, // MODEM
Win32_POTSModemToSerialPort, // MODEM port
Win32_DesktopMonitor, // Monitor
Win32_DisplayConfiguration, // Video card
Win32_DisplayControllerConfiguration, // Graphics settings
Win32_VideoController, //
Win32_VideoSettings, //
// Operating system
Win32_TimeZone, // Time zone
Win32_SystemDriver, // System Driver
Win32_DiskPartition, // Disk Partition
Win32_LogicalDisk, // Logical Disk
Win32_LogicalDiskToPartition, // Logical Disk To Partition
Win32_LogicalMemoryConfiguration, // Logical Memory Configuration
Win32_PageFile, // Page File
Win32_PageFileSetting, // Page File Setting
Win32_BootConfiguration, // Boot Configuration
Win32_ComputerSystem, // Computer information
Win32_OperatingSystem, // Operating system information
Win32_StartupCommand, // The system automatically starts the program
Win32_Service, // System installed services
Win32_Group, // Group
Win32_GroupUser, // Group users
Win32_UserAccount, // Group account
Win32_Process, // System process
Win32_Thread, // System thread
Win32_Share, // Share
Win32_NetworkClient, // Network Client
Win32_NetworkProtocol, // Network Protocol
Win32_PnPEntity,//all device
}
/// <summary>
/// Get available ports
/// </summary>
private string getAvailablePorts()
{
string[] ss = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name"); //Get PC hardware information
System.Collections.ArrayList portArray = new System.Collections.ArrayList();
try
{
for (var i = 0; i < ss.Length; i++)
{
if (ss[i].IndexOf("(") > -1 && ss[i].IndexOf(")") > -1)
{
portArray.Add(ss[i].Substring(ss[i].IndexOf("(") + 1, ss[i].IndexOf(")") - ss[i].IndexOf("(") - 1));
}
}
if (portArray.Count <= 0)
return "";
else
return portArray[0].ToString();
}
catch
{
MessageBox.Show("Get serial ports error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return "";
}
//if (portArray.Count > 0)
//{
// //cmbPortName.Items.AddRange(portArray.ToArray());
// //cmbPortName.SelectedIndex = 0;
// //return portArray[0].ToString ();
//}
}
/// <summary>
/// Get PC hardware information
/// </summary>
/// <param name="hardType"></param>
/// <param name="propKey"></param>
/// <returns></returns>
public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey)
{
List<string> strs = new List<string>();
try
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
{
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo["PNPDeviceID"].ToString().Contains(TWE_LITE_ID))
{
strs.Add(hardInfo.Properties[propKey].Value.ToString());
}
}
searcher.Dispose();
}
return strs.ToArray();
}
catch
{
return null;
}
finally
{ strs = null; }
}
如果搜索所有的串口号如下:
private void Form1_Load(object sender, EventArgs e)
{
try
{
string[] serialPortNames = SerialPort.GetPortNames();
foreach (string serialPortName in serialPortNames)
{
Invoke(new Action(() =>
{
cbxCOMPort.Items.Add(serialPortName);
}));
}
cbxCOMPort.SelectedIndex = serialPortNames.Length > 0 ? 0 : -1;
}
catch { }
}