LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#WinForm实现蓝牙连接文件传输

admin
2025年2月26日 7:39 本文热度 220

一、效果展示

二、VS2022
三、电脑开启蓝牙功能
手机接收到蓝牙连接
手机接收到蓝牙文件
四、核心代码
引用
    using InTheHand.Net;using InTheHand.Net.Sockets;using InTheHand.Net.Bluetooth;
    建立连接
      private BluetoothClient btClient;private NetworkStream btStream;private BluetoothDeviceInfo selectedDevice;private readonly Guid serviceUUID = new Guid("00001132-0000-1000-8000-00805f9b34fb"); // 标准SPP服务
      // 扫描蓝牙设备private void btnScan_Click(object sender, EventArgs e){ lstDevices.Items.Clear(); btClient = new BluetoothClient(); var devices = btClient.DiscoverDevices();
      foreach (var device in devices) { lstDevices.Items.Add($"{device.DeviceName} [{device.DeviceAddress}]"); }}
      // 设备选择private void lstDevices_SelectedIndexChanged(object sender, EventArgs e){ var selected = btClient.DiscoverDevices()[lstDevices.SelectedIndex]; selectedDevice = selected; richTextBox1.AppendText($"已选择:{selected.DeviceName}\n");}
      // 建立连接private void btnConnect_Click(object sender, EventArgs e){ try { btClient.Connect(selectedDevice.DeviceAddress, serviceUUID); btStream = btClient.GetStream(); StartListening(); richTextBox1.AppendText("连接成功\n"); } catch (Exception ex) { MessageBox.Show($"连接失败:{ex.Message}"); }}
      接收数据
        // 异步数据接收private void StartListening(){	new Thread(() =>	{		byte[] buffer = new byte[1024];		while (btClient?.Connected == true)		{			try			{				int bytesRead = btStream.Read(buffer, 0, buffer.Length);				if (bytesRead > 0)				{					string received = Encoding.UTF8.GetString(buffer, 0, bytesRead);					Invoke((MethodInvoker)delegate { richTextBox1.AppendText($"[接收] {received}\n"); });				}			}			catch { break; }		}	}).Start();}
        发送数据
          // 发送数据private void btnSend_Click(object sender, EventArgs e){	if (btClient?.Connected != truereturn;	// 读取文件并发送	byte[] buffer = new byte[1024]; // 缓冲区大小可以根据需要调整	using (FileStream fs = new FileStream(txtSend.Text, FileMode.Open, FileAccess.Read))	{		int bytesRead;		while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)		{			btClient.GetStream().Write(buffer, 0, bytesRead);		}	}	richTextBox1.AppendText($"[发送] {txtSend.Text}\n");	txtSend.Clear();}
          蓝牙Guid


          阅读原文:原文链接


          该文章在 2025/2/26 18:30:29 编辑过
          点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
          点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
          点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
          点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
          Copyright 2010-2025 ClickSun All Rights Reserved