C# 蓝牙编程

C#进行蓝牙编程

本节我们给大家用源码的形式给大家介绍如何用C#调用蓝牙。下面的源码是基于destop的C#调用蓝牙的程序,也就是使用普通版本的.NET Framework来调用编程,一般是有蓝牙的笔记本电脑,或者使用外接蓝牙设备的电脑,如何使用外接蓝牙设备,请参考:外接USB蓝牙设置无法启动

好了下面直接上代码:

using System;
sing System.Collections.Generic;
sing System.Windows.Forms;
sing InTheHand.Net;
sing InTheHand.Net.Bluetooth;
sing InTheHand.Net.Sockets;
 
amespace BlueTooth
 
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }
 
       BluetoothClient Blueclient = new BluetoothClient();
       Dictionary<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();
 
       private void btnFind_Click(object sender, EventArgs e)
       {
           this.lblMessage.Text = "";
           this.lblMessage.Visible = true;
           BluetoothRadio BuleRadio = BluetoothRadio.PrimaryRadio;
           BuleRadio.Mode = RadioMode.Connectable;
           BluetoothDeviceInfo[] Devices = Blueclient.DiscoverDevices();
           lsbDevices.Items.Clear();
           deviceAddresses.Clear();
           foreach (BluetoothDeviceInfo device in Devices)
           {
               lsbDevices.Items.Add(device.DeviceName);
               deviceAddresses[device.DeviceName] = device.DeviceAddress;
           }
 
           this.lblMessage.Text = "搜索设备完成,搜索到" + lsbDevices.Items.Count + "个蓝牙设备。";
 
       }
 
       private void btnConnect_Click(object sender, EventArgs e)
       {
           try
           {
               BluetoothAddress DeviceAddress = deviceAddresses[lsbDevices.SelectedItem.ToString()];
               Blueclient.SetPin(DeviceAddress, txtPwd.Text.Trim());
               Blueclient.Connect(DeviceAddress, BluetoothService.Handsfree); 
               MessageBox.Show("配对成功。");
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
           }
       }
   }

上图是点击finddevices按钮后的结果。我们选择其中的一个设备,然后在Password的textbox中输入配对密码,点击Connect,如果成功会弹出对话框提示“配对成功”,如果失败会出现如下提示:

 

Note:你只要想在Visual Studio中建立一个winform的默认程序,并把代码复制过去,然后引用InTheHand.Net.Personal.dll你的程序就可以直接运行了。不过我不建议你直接复制,最好是敲一边代码比较好。

上面的示例代码中还需要特殊注意的就是下面这三个命名空间:

using InTheHand.Net; 
using InTheHand.Net.Bluetooth; 
using InTheHand.Net.Sockets;

他们是拿来的呢?在上面的程序中我引用了一个外部的DLL:InTheHand.Net.Personal.dll,上面那三个命名空间就是InTheHand.Net.Personal.dll中的。我使用的是桌面版的.NET Framework3.5,如果你想在移动设备,如手机或者手持机等移动设备而上使用,那么你只需要创建一个.NET Compact  Framework 3.5的程序,把上面的源码直接复制过去,并且引用InTheHand.Net.Personal.dll的移动版本就ok了。

总结

本文介绍了蓝牙技术以及用C#写了一个调用蓝牙的实例Demo,帮助大家理解,希望对大家有所帮助。我在这里留下一个悬念就是InTheHand.Net.Personal.dll是怎么来的,请参考:.NET蓝牙开源库:32feet.NET

转载自:http://www.cnblogs.com/sczw-maqing/p/3329750.html

posted @ 2016-11-18 14:52  未来,已来  阅读(17820)  评论(0编辑  收藏  举报