使用Delphi列出蓝牙设备

欢迎加入全网最大Delphi 技术交流群 682628230

在使用Delphi进行蓝牙开发时,列出所有连接到特定蓝牙适配器(主机设备)的蓝牙设备是一项基本任务。以下是如何实现这一功能的核心步骤和代码片段。

实现方法

通过JEDI API JwaBluetoothAPIs库可以实现蓝牙设备的查找与列举。首先,确保包含了必要的单元JwaBluetoothAP

uses
  JwaBluetoothAPIs;

procedure ScanBluetoothRadiosDevices;
var
  RadioHandle, DeviceFindHandle: THandle;
  BtFrp: TBlueToothFindRadioParams;
  RadioInfo: BLUETOOTH_RADIO_INFO;
  DeviceInfo: BLUETOOTH_DEVICE_INFO;
  DeviceSearchParams: BLUETOOTH_DEVICE_SEARCH_PARAMS;
begin
  // 设置记录大小
  BtFrp.dwSize := SizeOf(BtFrp);
  DeviceInfo.dwSize := SizeOf(DeviceInfo);
  RadioInfo.dwSize := SizeOf(RadioInfo);

  // 查找第一个蓝牙适配器
  if BluetoothFindFirstRadio(@BtFrp, RadioHandle) = 0 then
    RaiseLastOSError;

  repeat
    // 启用发现模式并获取适配器信息
    BluetoothEnableDiscovery(RadioHandle, True);
    if BluetoothGetRadioInfo(RadioHandle, RadioInfo) = ERROR_SUCCESS then
      ShowMessage('Radio found: '+ RadioInfo.szName);

    // 配置搜索参数
    with DeviceSearchParams do
    begin
      dwSize := SizeOf(DeviceSearchParams);
      fReturnUnknown := True;
      fReturnRemembered := True;
      hRadio := RadioHandle;
    end;

    // 查找设备
    if BluetoothFindFirstDevice(DeviceSearchParams, DeviceInfo) <> 0 then
      repeat
        if BluetoothGetDeviceInfo(RadioHandle, DeviceInfo) = ERROR_SUCCESS then
        begin
          BluetoothUpdateDeviceRecord(DeviceInfo);
          if DeviceInfo.fConnected then
            ShowMessageFmt('Device %s is connected', [DeviceInfo.szName])
          else
            ShowMessageFmt('Device %s is not connected', [DeviceInfo.szName]);
        end;
      until not BluetoothFindNextDevice(DeviceFindHandle, DeviceInfo);
  until not (BluetoothFindNextRadio(FindHandle, RadioHandle));
end;

该代码段展示了如何初始化蓝牙查找参数,启用蓝牙发现,并循环遍历所有蓝牙适配器及其关联的设备,最终输出每个设备的连接状态。注意,实际应用中应根据需要替换ShowMessageFmt为自定义逻辑

Is,然后按照如下代码结构进行:

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享