【问题标题】:How to get COM port using 32feet in c#?如何在 C# 中使用 32feet 获取 COM 端口?
【发布时间】:2015-10-08 06:09:09
【问题描述】:

如何获得通过蓝牙棒连接移动设备的 COM 端口?我已经可以得到设备的名称,例如。 'Nokia C2-01' 和 device.DeviceName 使用 32feet library 但我怎样才能让它看起来像这样? "Nokia c2-01 connected through COM7"?

【问题讨论】:

    标签: c# visual-studio bluetooth serial-port 32feet


    【解决方案1】:

    首先,您需要使用以下方式获取设备地址:

    string comPort = GetBluetoothPort(device.DeviceAddress.ToString());
    if(!string.IsNullOrWhiteSpace(comPort))
    {
         // enter desired output here
    }
    

    GetBluetoothPort() 方法如下所示:

    using System.Management;
    private string GetBluetoothPort(string deviceAddress)
        {
            const string Win32_SerialPort = "Win32_SerialPort";
            SelectQuery q = new SelectQuery(Win32_SerialPort);
            ManagementObjectSearcher s = new ManagementObjectSearcher(q);
            foreach (object cur in s.Get())
            {
                ManagementObject mo = (ManagementObject)cur;
                string pnpId = mo.GetPropertyValue("PNPDeviceID").ToString();
    
                if (pnpId.Contains(deviceAddress))
                {
                    object captionObject = mo.GetPropertyValue("Caption");
                    string caption = captionObject.ToString();
                    int index = caption.LastIndexOf("(COM");
                    if (index > 0)
                    {
                        string portString = caption.Substring(index);
                        string comPort = portString.
                                      Replace("(", string.Empty).Replace(")", string.Empty);
                        return comPort;
                    }
                }              
            }
            return null;
        }
    

    这将返回端口名称,即 COM7

    【讨论】:

    • 如果设备暴露了多个comport,有没有办法将每个comport映射到特定的ServiceRecord
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多