Способы подключения устройств Bluetooth к ПК: примеры кода и учебные пособия

Чтобы установить соединение Bluetooth на ПК, существует несколько способов. Вот несколько подходов и примеры кода для подключения устройства Bluetooth к ПК:

Метод 1. Использование API Windows Bluetooth (C#)

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    static void Main(string[] args)
    {
        Process.Start("explorer.exe", "shell:::{28803F59-3A75-4058-995F-4EE5503B023C}");
        Thread.Sleep(2000);
        IntPtr handle = Process.GetProcessesByName("explorer")[0].MainWindowHandle;
        SendMessage(handle, 0x111, 28931, 0);
    }
}

Метод 2. Использование библиотеки pybluez (Python)

import bluetooth
# Discover nearby devices
devices = bluetooth.discover_devices()
for device in devices:
    print(f"Device: {device} - {bluetooth.lookup_name(device)}")

Способ 3: использование утилит BlueZ (Linux)
Откройте терминал и выполните следующие команды:

# Scan for nearby devices
hcitool scan
# Pair with a device
bluetoothctl
agent on
default-agent
scan on
pair <device_address>
trust <device_address>
connect <device_address>