C# 藍牙編程

C#進行藍牙編程

本節咱們給你們用源碼的形式給你們介紹如何用C#調用藍牙。下面的源碼是基於destop的C#調用藍牙的程序,也就是使用普通版本的.NET Framework來調用編程,通常是有藍牙的筆記本電腦,或者使用外接藍牙設備的電腦,如何使用外接藍牙設備,請參考:外接USB藍牙設置沒法啓動html

好了下面直接上代碼:編程

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,若是成功會彈出對話框提示「配對成功」,若是失敗會出現以下提示:this

 

Note:你只要想在Visual Studio中創建一個winform的默認程序,並把代碼複製過去,而後引用InTheHand.Net.Personal.dll你的程序就能夠直接運行了。不過我不建議你直接複製,最好是敲一邊代碼比較好。spa

上面的示例代碼中還須要特殊注意的就是下面這三個命名空間:.net

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

他們是拿來的呢?在上面的程序中我引用了一個外部的DLL:InTheHand.Net.Personal.dll,上面那三個命名空間就是InTheHand.Net.Personal.dll中的。我使用的是桌面版的.NET Framework3.5,若是你想在移動設備,如手機或者手持機等移動設備而上使用,那麼你只須要建立一個.NET Compact  Framework 3.5的程序,把上面的源碼直接複製過去,而且引用InTheHand.Net.Personal.dll的移動版本就ok了。orm

總結

本文介紹了藍牙技術以及用C#寫了一個調用藍牙的實例Demo,幫助你們理解,但願對你們有所幫助。我在這裏留下一個懸念就是InTheHand.Net.Personal.dll是怎麼來的,請參考:.NET藍牙開源庫:32feet.NEThtm

轉載自:http://www.cnblogs.com/sczw-maqing/p/3329750.htmlblog

相關文章
相關標籤/搜索