C# 连接蓝牙

最近在学习蓝牙通讯,看了很多文章有位大佬的很有用,在此总结一下:

1.下载DLL包

32feet.NET

2.粘贴代码

public static void LanYa(string MAC)
        {
            BluetoothClient client = new BluetoothClient();
            BluetoothRadio radio = BluetoothRadio.PrimaryRadio;
            radio.Mode = RadioMode.Connectable;
            BluetoothAddress blueAddress = null;
            Console.WriteLine("开始搜索蓝牙!请等待10S");
            BluetoothDeviceInfo[] devices = client.DiscoverDevices();
            Thread.Sleep(50);
            bool connt = false;
            foreach (var item in devices)
            {
                if (item.DeviceAddress.ToString()==MAC)
                {
                    Console.WriteLine("搜索到蓝牙:" + item.DeviceAddress);
                    connt = true;
                    Console.WriteLine("准备连接!");
                    blueAddress = item.DeviceAddress;
                    BluetoothEndPoint ep = new BluetoothEndPoint(blueAddress, BluetoothService.Handsfree);//BluetoothService.SerialPort
                    client.Connect(ep);
                    if (client.Connected)
                    {
                        Console.WriteLine("连接成功!");
                    }
                    else
                    {
                        Console.WriteLine("连接失败!");
                    }
                    break;
                }
            }

            if (connt==false)
            {
                Console.WriteLine("没有找到蓝牙:"+ MAC);
            }
            else
            {
                Console.WriteLine("连接成功!");
            }
            Console.Read();
        }

3.调用就行 

string MAC = "2032C6E06AA6";//2032C6E06AA6
LanYa(MAC);

4.通讯功能

关于通讯功能我暂时记录在这里,等有条件的时候再验证,或者有哪个好兄弟验证了麻烦留言在评论区,小编感激不尽;

public static void Senddata(BluetoothClient client,string dataToSend =  "Hello, Bluetooth!")
        {
            NetworkStream stream = client.GetStream();

            byte[] data = Encoding.UTF8.GetBytes(dataToSend);

            // 发送数据
            stream.Write(data, 0, data.Length);

            using (StreamReader reader = new StreamReader(stream))
            {
                // 读取数据
                Console.WriteLine("Received data: " + reader.ReadLine());// 或者使用需要的读取方法
            }
            // 关闭连接
            client.Close();
        }

 大佬文章:C#连接蓝牙设备_c# 蓝牙-CSDN博客 

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值