C# 获取计算机串口列表

C# 获取计算机串口列表功能实现。

第一步:引入库文件:"kernel32.dll"

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

第二步:获取串口列表(两种方法)

方法一:从计算机注册表的特定位置读取出串口信息。返回:从注册表获取系统串口列表

public static string[] GetComList()
{
    try
    {
        RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
#if TEST
        OutputDebugString(keyCom.ToString());
#endif
        string[] sSubKeys = keyCom.GetValueNames();
        string[] rtn = new string[sSubKeys.Length];
        for (int i = 0; i < sSubKeys.Length; i++)
        {
            rtn[i] = (string)keyCom.GetValue(sSubKeys[i]);
        }
        return rtn;
    }
    catch (Exception e)
    {
#if TEST
        OutputDebugString(e.Message);
#endif
        return null;
    }
}

方法二:利用.NET下提供的SerialPort类具体如下

public static string[] GetPort()
{
    try
    {
        RegistryKey hklm = Registry.LocalMachine;

        RegistryKey software11 = hklm.OpenSubKey("HARDWARE");

        //打开"HARDWARE"子健
        RegistryKey software = software11.OpenSubKey("DEVICEMAP");

        RegistryKey sitekey = software.OpenSubKey("SERIALCOMM");
#if TEST
        OutputDebugString(sitekey.ToString());
#endif
        //获取当前子健
        String[] Str2 = sitekey.GetValueNames();

        //获得当前子健下面所有健组成的字符串数组
        int ValueCount = sitekey.ValueCount;
        //获得当前子健存在的健值
        int i;
        string[] rtn = new string[ValueCount];
        for (i = 0; i < ValueCount; i++)
        {
            rtn[i] = (string)sitekey.GetValue(Str2[i]);
        }
        return rtn;
    }
    catch (Exception e)
    {
#if TEST
        OutputDebugString(e.Message);
#endif
        return null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值