Friday, January 4, 2013

Bluetooth c# code sample

Here's a quick code sample of how to scan for Bluetooth devices and display some properties of that device.  This was deployed to a Motorola hand held device.  The framework is the Compact Framework and the Bluetooth functionality is made possible by the InTheHand.Net.Personal API.


using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Windows;

namespace SmartDeviceProject2
{
    public partial class Form1 : Form
    {
        private BluetoothClient _btc;
        private BluetoothDeviceInfo[] _peers;
       
       
        public Form1()
        {
            InitializeComponent();
            this.devicesListBox.Items.Clear();

            _btc = new BluetoothClient();
            _peers = _btc.DiscoverDevices();

            deviceInfoLbl.Text = string.Empty;
           
        }

        private void scanButton_Click(object sender, EventArgs e)
        {

            deviceInfoLbl.Text = string.Empty;

         
           
            this.devicesListBox.DisplayMember = "DeviceName";
            this.devicesListBox.ValueMember = null;
            this.devicesListBox.DataSource = _peers;




        }

        private void devicesListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            deviceInfoLbl.Text = getDeviceInfo(devicesListBox.SelectedIndex);
           
        }

        private string getDeviceInfo(int index)
        {
            string ret = string.Empty;


            try
            {              
                string connectedText = "No";
                if (_peers[index].Connected)
                    connectedText = "Yes";
               
                ret = string.Format("Device Name: {0}\nDevice Address: {1}\nDevice Class: {2}\nConnected: {3} ",
                    _peers[index].DeviceName,
                    _peers[index].DeviceAddress.ToString(),
                    _peers[index].ClassOfDevice.ToString(),
                    connectedText);
            }
            catch (Exception e)
            {
                deviceInfoLbl.Text = string.Empty;
                return ret;
            }


            return ret;

        }
    }
}





No comments: