畫面中 [SearchDevices] 尋找 BlueTooth 設備,選擇欲連線之設備 (此範例為:MP3200BT-8005),按下 [Connect] 與其設備連線。並且可利用 [SendByte] 鈕與 BTPrinter 溝通。
using與變數定義如下:
using InTheHand.Net.Bluetooth; using InTheHand.Net.Sockets; private BluetoothClient bluetoothClient; private Guid service = BluetoothService.SerialPort;BluetoothService.SerialPort這個搞了我好久,原本範例中的變數定義為BluetoothService.DialupNetworking,但始終都沒有連上線,所以提醒大家不妨先看看自己要連線的設備規格再去做選擇以甚麼樣的方式連線。
搜尋設備之程式如下:
private void btnSearch_Click(object sender, EventArgs e) { // 先 new 一個 bluetoothClient bluetoothClient = new BluetoothClient(); Cursor.Current = Cursors.WaitCursor; // 存放 bluetooth 設備資訊 BluetoothDeviceInfo[] bluetoothDeviceInfo = { }; // 利用 new 出來的 bluetoothClient 搜尋 buletoothDevices bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10); // 搜尋到的設備資訊放至 Combobox 中 cmbBTDev.DataSource = bluetoothDeviceInfo; // 顯示為 DeviceName cmbBTDev.DisplayMember = "DeviceName"; // 值為 DeviceAddress(Connect 時會用到) cmbBTDev.ValueMember = "DeviceAddress"; cmbBTDev.Focus(); Cursor.Current = Cursors.Default; }[Connect] 程式如下:
private void btnConnect_Click(object sender, EventArgs e) { if (cmbBTDev.SelectedValue != null) { try { //先將Combobox之value轉換為BluetoothAddress,之後再轉為BluetoothEndPoint並利用serialport連線 bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)cmbBTDev.SelectedValue, service)); MessageBox.Show("Connected"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }[SendByte]程式如下:
if (bluetoothClient.Connected == true) { //FullCmd為byte[] bluetoothClient.Client.Send(FullCmd); }目前以上面程式完成連線並成功傳值至Bluetooth設備,當然傳甚麼樣的值要參考每個設備的protocol,因此在此不做示範。下次見:)
MP3200 簡介:http://www.cino.com.tw/products/mp/mp3200.htm
InTheHand 元件:http://inthehand.com/content/32feet.aspx
程式參考:codeproject