如何使用制定的外置蓝牙模块连接设备?先找到设备然后再使用这个设备去连接外部蓝牙?这是我最开始的思路,但是没有实现,主要原因是我并不能控制具体哪个蓝牙去连接外部设备。那么咋办呢?后来灵光乍现啊,我把所有的蓝牙都禁用掉,然后就启用指定的蓝牙就可以了。哈哈哈~!
具体代码如下:
private void SetDeviceEnable()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%Bluetooth%'");
foreach (ManagementObject item in searcher.Get())
{
BlueTooth = item;
DeviceDisable();
}
foreach (ManagementObject item in searcher.Get())
{
Debug.WriteLine($"Device Name: {item["Caption"]}");
Debug.WriteLine($"Manufacturer: {item["Manufacturer"]}");
//指定蓝牙的名称
if (item["Caption"].ToString() == "Realtek Bluetooth 5.3 Adapter" && item["Manufacturer"].ToString() != "Microsoft")
{
BlueTooth = item;
DeviceEnable();
}
}
}
catch (Exception ex)
{
}
}
ManagementObject BlueTooth = null;
//启用方法
public void DeviceEnable()
{
if (BlueTooth == null)
{
return;
}
try
{
BlueTooth.InvokeMethod("Enable", null);
}
catch (Exception e)
{
//throw new Exception(e.Message);
}
}
//禁用方法
public void DeviceDisable()
{
if (BlueTooth == null)
{
return;
}
try
{
BlueTooth.InvokeMethod("Disable", null);
}
catch (Exception e)
{
//throw new Exception(e.Message);
}
}