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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM