How can I find out a COM port number of a bluetooth device in c#?

后端 未结 6 976
逝去的感伤
逝去的感伤 2020-12-10 02:44

My company developed a device that communicates with a PC via Bluetooth using a virtual COM port.

Now we need a user to pair a device with a PC (MS Windows OS) firs

6条回答
  •  醉梦人生
    2020-12-10 03:04

    First, create a Management Object Searcher to search the WMI database:

    ManagementObjectSearcher serialSearcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_SerialPort");
    

    Next, use LINQ to get all the serial ports into a query:

    var query = from ManagementObject s in serialSearcher.Get()
                select new { Name = s["Name"], DeviceID = s["DeviceID"], PNPDeviceID = s["PNPDeviceID"] }; // DeviceID -- > PNPDeviceID
    

    You can now print all the COM ports, their friendly names and you can even filter through their PNPDeviceID's to find the bluetooth device address. Here's an example:

    foreach (var port in query)
    {
        Console.WriteLine("{0} - {1}", port.DeviceID, port.Name);
        var pnpDeviceId = port.PNPDeviceID.ToString();
    
        if(pnpDeviceId.Contains("BTHENUM"))
        {
            var bluetoothDeviceAddress = pnpDeviceId.Split('&')[4].Split('_')[0];
            if (bluetoothDeviceAddress.Length == 12 && bluetoothDeviceAddress != "000000000000")
            {
                Console.WriteLine(" - Address: {0}", bluetoothDeviceAddress);
            }
        }
    }
    

提交回复
热议问题