10

Everything I found online regarding bluetooth LE requires a universal windows app, which is completely unsuitable for me.

Is there a way to use bluetooth LE from c# without having to write my whole app as on UWP?

Cedric Mamo
  • 1,724
  • 2
  • 18
  • 33

3 Answers3

21

You can use C# APIs in C# Desktop applications! I have a sample here in GitHub.

In general, to get access to the C# APIS, add two references to your project:

  1. C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd
  2. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

Note that the #2 version depends on the version of .NET that you're using.

Background tasks will not be supported, but all other Bluetooth C# features should be there.

Jake Smith
  • 2,332
  • 1
  • 30
  • 68
Carter
  • 3,053
  • 1
  • 17
  • 22
  • I tried that. Worked on windows 8, couldn't get it to work on windows 10 though. I have no idea what I did wrong. Also the bluetooth LE api is severely limited in windows 8. So while I can target the windows 8 ones and still run in windows 10, that just won't work for me. I need to use windows 10's bluetooth LE api – Cedric Mamo May 20 '16 at 08:46
  • @CedricMamo Just tried doing this myself- updating the answer now! – Carter May 20 '16 at 22:00
  • It seems #2 can be found under a different path on my os `C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll` – Peter Mar 27 '17 at 18:13
  • What would it take to access this from PowerShell? – uSlackr Oct 08 '18 at 01:24
  • If I add these two references, I still don't have access to `Windows.Devices` – Jake Smith Nov 12 '18 at 18:42
  • Looks like the Windows SDK references can be added by installing the `Microsoft.Windows.SDK.Contracts` [NuGet package](https://www.nuget.org/packages/Microsoft.Windows.SDK.Contracts) – Amir Mahdi Nassiri May 18 '21 at 19:48
  • @AmirMahdiNassiri I tried - it doesn't recognize "Windows.Devices". – JustAMartin Oct 06 '21 at 13:01
  • The file C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd is not there also after the latest update – qwlice Dec 09 '21 at 11:51
  • I've tried your solution but Visual Studio Community 2022 tells me these APIS are already included and your example code seems to work. It would be nice to add more code like to connect/disconnect. – IVIike Jun 14 '23 at 10:30
1

I have worked with and around the Microsoft partial Bluetooth API solutions since the XP days. I found a library from BTFramework that I have used extensively, on many platforms and in several languages. The Bluetooth Classic and Low Energy API packages from BTFramework have been easy to use, very reliable, and they've been super-responsive to any defects I did find. Our commercial product, as a result, has zero failures arising from the Bluetooth side. The team at BTFramework has taken on the job of working around Microsoft's partial implementations of the standard. We mainly code in C# dot NET, by the way. And we use many threads in the application.

  • Thanks for the reference. Sometimes a 3rd party solution to a particularly thorny problem is the sensible answer. I will check them out... – batpox Jan 19 '20 at 23:08
0
Look at the code below this shows how to scan and connect to a ble device using winform application

using System;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;

namespace TestBle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_ClickAsync(object sender, EventArgs e)
        {
            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

            DeviceWatcher deviceWatcher =
                        DeviceInformation.CreateWatcher(
                                BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                                requestedProperties,
                                DeviceInformationKind.AssociationEndpoint);

            // Register event handlers before starting the watcher.
            // Added, Updated and Removed are required to get all nearby devices
            deviceWatcher.Added += DeviceWatcher_Added;
            deviceWatcher.Updated += DeviceWatcher_Updated;
            deviceWatcher.Removed += DeviceWatcher_Removed;
            deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
            deviceWatcher.Stopped += DeviceWatcher_Stopped;

            // Start the watcher.
            deviceWatcher.Start();
        }

        private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
        {
            //throw new NotImplementedException();
        }

        private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
        {
            string a = "";
        }

        private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
        {
            string a = "";
        }

        private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
        {
            string a = "";
        }

        private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            string[] split = args.Id.Split('-');
            if(split[1] == "84:2e:14:aa:65:13")
            {
                BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(args.Id);
                GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();

                if (result.Status == GattCommunicationStatus.Success)
                {
                    var services = result.Services;
                    // ...
                }
            }`enter code here`

        }
    }
}
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '21 at 16:11