Georgi Koemdzhiev
Georgi Koemdzhiev

Reputation: 11931

How to discover only printer Bluetooth devices in C#?

I am developing an app that implements Bluetooth printing. As part of this process, I want to limit the discovered devices by type - only printer devices. Currently, the code that I use to discover Bluetooth devices is the following:

 public List<ScannerInfo> GetPrinters()
    {
        // Declare results
        List<ScannerInfo> result = new List<ScannerInfo>();

        // Get all the bluetooth and bluetooth serial devices
        DeviceInformationCollection pairedBluetoothDevices = Task.Run(async () =>
            await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector())).Result;
        DeviceInformationCollection pairedBluetoothSerialDevices = Task.Run(async () =>
                await DeviceInformation.FindAllAsync(
                    RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)))
            .Result;

        // Get scanner data
        foreach (DeviceInformation pairedBluetoothSerialDevice in pairedBluetoothSerialDevices)
        {
            var d = DeviceInformation.CreateFromIdAsync(pairedBluetoothSerialDevice.Id);
            // Create object
            ScannerInfo newScanner = new ScannerInfo
            {
                Id = pairedBluetoothSerialDevice.Id,
                Name = pairedBluetoothSerialDevice.Name
            };

            // Correct name (this is necessary as following the anniversary update the serial object name no longer holds the bluetooth device name, only the prototcol name.
            // Therefore we attempt to get this by matching id components via the full bluetooth device list, which is what the user sees in windows settings).
            foreach (var pairedBluetoothDevice in pairedBluetoothDevices)
            {
                if (pairedBluetoothSerialDevice.Id.Contains(pairedBluetoothDevice.Id))
                {
                    newScanner.Name = pairedBluetoothDevice.Name;
                    break;
                }
            }

            // Add to result set
            result.Add(newScanner);
        }

        // Return items
        return result;
    }

Upvotes: 1

Views: 764

Answers (1)

Xie Steven
Xie Steven

Reputation: 8611

You could try to use Advanced Query Syntax (AQS) filter as selector for DeviceInformation.FindAllAsync method to filter printer devices.

In this document Quickstart: enumerating commonly used devices, it uses {0ECEF634-6EF0-472A-8085-5AD023ECBCCD} as PrinterInterfaceClass GUID, you could try it.

The Build a device selector was also for your details.

Upvotes: 1

Related Questions