Loading user information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading user information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Bluetooth ScreenLock

 Bluetooth ScreenLock is a sample application built on top of the Bluetooth managed wrappers that are included in the Coding4Fun Developer Toolkit.
Clarity Consulting, Inc.

Difficulty: Easy
Time Required: 1-3 hours
Cost: Free
Software: Visual Studio 2008 Express Editions Beta 2, Coding4Fun Developer Toolkit (Bluetooth assemblies)
Hardware: Bluetooth-enabled laptop and phone.
Download: Download

The Coding4Fun Developer Kit that was released to CodePlex last month contains a bunch of neat libraries and components for jumpstarting development against some of the new features of Vista. Included in the kit is a managed wrapper around Bluetooth communication that is designed to run in non-mobile environments – something that has not previously been widely available. With most newer laptops shipping with Bluetooth radios, and the proliferation of Bluetooth devices and receivers, I looked forward to trying this out. To get familiar with the managed wrappers, I built a simple screen locking application that I call Bluetooth Screenlock. The Bluetooth ScreenLock application runs on your PC, connects to your phone, and when it detects that you've walked out of range, locks your workstation. Using the Bluetooth wrappers included in the Coding4Fun Developer Toolkit makes this pretty simple.

Bluetooth Profiles

The managed Bluetooth wrapper classes that are part of the Coding4Fun Developer Kit (C4F Kit) contain libraries for connecting to three different Bluetooth profiles: Serial Port, File Transfer and Object Push. A profile is a standardized interface specification that devices comply to in order to communicate with each other. For the Bluetooth ScreenLock application I used the Serial Port profile to establish a connection and then send heartbeat messages across the Bluetooth channel periodically. If any heartbeat were to fail, the program will lock the user's workstation.

Discovery and Pairing

Discovery is the process of detecting nearby Bluetooth devices and potentially asking them to enumerate their supported services. In order to discover a device and enumerate its services, one of two things must happen: The phone must be set to discovery mode, which enables any other Bluetooth device to see it, or the two devices must be paired. Note for security reasons you generally don't want to leave your phone set up as discoverable.

Pairing is the process of establishing a trust relationship between two devices. Pairing usually involves the exchange of a key pair – a pin-like series of digits that must be entered on both devices before the trust relationship is established. In order to use the Bluetooth ScreenLock application you must pair your phone to your PC. You can start this from the PC, or from your phone. In Vista you can start the pairing process by opening the Bluetooth Devices utility and clicking the Add button on the Devices tab (see Figure 1).  Note that I built and tested the application with a Motorola Q smartphone.

Figure 1 - The Bluetooth Devices utility in Vista

Once you've paired your phone to your PC, you can use the application. I decided to build the application as a Windows Forms application, but it just as easily could have been a Windows Service set to start automatically. The form is simple – just a combo box listing nearby devices and a button to enable the ScreenLock feature. It would be a pretty easy exercise to configure the application to automatically enable itself at Windows startup.

Figure 2 - The ScreenLock window

Connecting to a device

The code for the ScreenLock application uses just two of the functions in the C4F toolkit – DiscoverDeviceByName and DiscoverServicesByType. DiscoverDeviceByName is used to get an instance of a Device, which is a managed class exposed through the C4F.DevKit.Bluetooth.DeviceAndServiceDiscovery assembly.


public bool DiscoverDevice(string deviceName){    bool returnValue = false;    try    {        DeviceServicesManager _manager = new DeviceServicesManager();        SelectedDevice = _manager.DiscoverDeviceByName(deviceName);        if (SelectedDevice != null)        {            returnValue = true;        }    }    catch (Exception ex)    {        throw new Exception("An unexpected error was raised during device discovery." + Environment.NewLine + ex.Message);    }    return returnValue;} 


Public Function DiscoverDevice(ByVal deviceName As String) As Boolean    Dim returnValue As Boolean = False    Try        Dim _manager As DeviceServicesManager = New DeviceServicesManager()        SelectedDevice = _manager.DiscoverDeviceByName(deviceName)        If Not SelectedDevice Is Nothing Then            returnValue = True        End If    Catch ex As Exception        Throw New Exception("An unexpected error was raised during device discovery." & Environment.NewLine & ex.Message)    End Try    Return returnValue End Function

Once you have an instance of a Device, you can get a handle to the serial port service by calling DiscoverServicesByType.  After that you could connect directly to the service on the device:


public bool Connect(){    bool returnValue = false;    List<RemoteService> serviceList = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile);    RemoteService remoteService = null;    try    {        remoteService = serviceList[0];        _stream = remoteService.Connect();        _connectedService = remoteService;        returnValue = true;    }    catch (ServiceConnectionException servEx)    {        throw new Exception("An error occurred while trying to connect to " + remoteService.Name + Environment.NewLine + "Error Details: " + servEx.Message);    }    catch    {        throw;    }    return returnValue;}
Public Function Connect() As Boolean    Dim returnValue As Boolean = False    Dim serviceList As List(Of RemoteService) = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile)    Dim remoteService As RemoteService = Nothing    Try        remoteService = serviceList(0)        _stream = remoteService.Connect()        _connectedService = remoteService        returnValue = True    Catch servEx As ServiceConnectionException        Throw New Exception("An error occurred while trying to connect to " & remoteService.Name & Environment.NewLine & "Error Details: " & servEx.Message)    Catch        Throw    End Try    Return returnValue End Function

Bluetooth devices are recognized by their 48-bit address, but most devices use a friendly name to identify themselves. The friendly name can usually be changed by the owner of the device. The ScreenLock application allows the user to specify the friendly name to use to connect, or to search for paired devices (in the case where they don't know the device name). To search for nearby devices the app uses the DiscoverAllDevices function with returns a list of Device objects. Since we only need the device names to populate our combo box, we use a simple LINQ query to extract the names and project them into a List of type string:


public List<string> DiscoverDevices(){    var q =        from device in _manager.DiscoverAllDevices()        select device.Name;    return q.ToList<string>();}


Public Function DiscoverDevices() as List(Of String)   Dim result As List(Of String) = New List(Of String)   For Each d As Device in _manager.DiscoverAllDevices()      result.Add(d.Name)   Next   Return result End Function

Once a device is connected to the serial port profile, the application simply uses a timer to periodically write a byte of text to the port. If the transmission fails for any reason, the application will lock the workstation by calling the LockWorkstation API call from user32.dll.


public bool Ping(){    bool returnValue = true;    if (!object.Equals(_stream,null)) {        try        {            _stream.WriteByte(1);        }        catch (Exception ex)        {            returnValue = false;        }    }    return returnValue;}


Public Function Ping() As Boolean    Dim returnValue As Boolean = True    If (Not Object.Equals(_stream,Nothing)) Then        Try            _stream.WriteByte(1)        Catch ex As Exception            returnValue = False        End Try    End If    Return returnValue End Function 

The excellent Coding4Fun Developer Toolkit hides all of the complexity of setting up socket connections using the Bluetooth protocol and exposes a few simple but useful functions for interacting with Bluetooth devices from managed code. If you're interested in writing Bluetooth apps in managed code, I suggest you take a look at it – it includes several detailed samples. In addition to the Bluetooth wrapper, there several other cool samples, such as those showing you how to write your own Preview Handlers and interact with Windows Vista Contacts.


Follow the discussion

  • Oops, something didn't work.

    Getting subscription
    Subscribe to this conversation
  • rbelknaprbelknap

    Has anyone had success using the IOGEAR GBU421 usb/bluetooth adapter. I can get the program to compile, but it does not see any devices.

  • JackJack

    No problems after installing the C4F framework and changing "DeviceServicesManager" to "BluetoothDeviceServicesManager". Although, if you're using the toshiba stack, you may have issues; I solved the problem by removing the "Bluetooth Stack by Toshiba for Windows" (or whatever it's called) from add/remove programs, and then letting windows find and install the drivers. Using an LG Dare on a Toshiba 350 bluetooth card inside of a dell laptop.

  • charles justicecharles justice

    i love all your works and article,but looka this problem i have,am in final year and my project supervisor gave me topic to work on "design and implementation of a bluetooth communication software" and i have tried to design d interface and the source code but to no avail could you please help me out cos i have just 2weeks please save.thanks.you can send through this e-mail charlesjustice65@yahoo.com. am counting on u.

  • charles justicecharles justice

    i love all your works and article,but looka this problem i have,am in final year and my project supervisor gave me topic to work on "design and implementation of a bluetooth communication software" and i have tried to design d interface and the source code but to no avail could you please help me out cos i have just 2weeks please save.thanks.you can send through this e-mail charlesjustice65@yahoo.com. am counting on u.

  • Clint RutkasClint I'm a "developer"

    @Charles Justice: Not sure what your issue is?  Did you try http://www.codeplex.com/C4FDevKit for the bluetooth part by itself?

  • Clint RutkasClint I'm a "developer"

    @Bernard, click the "Email Us" link so I can get a better detail on this and help resolve this issue.  Like I said, I have to hunt down an iphone which may be a tad harder right now due to holidays.  Looking at the code in the article, not totally sure why he is calling it a serial port.  Jerry looks to just be sending some data over to verify the device is actually there.

    Also to submit a patch, here is the link from codeplex on the c4f dev kit.


  • BernardBernard

    When I enumerate the services, there are 8, none of which are SPP. I see other things like wireless access point and voice. I was hoping I could connect to any of them, but every service rejects my Connect() call.

    My last ditch effort will be to DiscoverDevices every few seconds and compare the list, but that seems horribly inefficient. Any help is appreciated, I also found a few places in your helper class to add error checking for this type of situation. Happy to contribute back. Thanks Charles.

  • Clint RutkasClint I'm a "developer"

    @Bernard that is an excellent question, my problem is I don't have an iphone to test this against.  My gut says this should work.  Let me see if I can't track down someone that will let me borrow one for a day or two.

  • BernardBernard

    Does not work with many phones, since they do not support Serial Port Profile. IPhone included L(

    What other service could you connect to? Hands Free? If so, how? Thank you Charles.

  • Z8080Z8080

    I have a C# application (VS2008 using .NET 3.6) for the Blue Toothe connecity using the C4F libraries. The application can discover any BT enabled devices within the range and it works fine. However, I want the application should auto-detect any BT enabled device (on discovery mode) as soon as it comes in within the range. Is there any better way to that? Highly appreciate any recommendation of how to handle this case.

  • BuragohainMBuragohainM

    Put the discovery function in a infinite loop with a time interval in a background worker thread and keep your GUI updated if new one found.

  • Clint RutkasClint I'm a "developer"

    @Zman email us, I think I can help out, I just need greater context.  Contact link is in the upper right.

  • ZmanZman

    I can discover and pair a bluetooth device in my C# application, but I'm stuck in assigning com ports (incoming or outgoing) to that remote device. I highly appreciate any help on this. Thank you.

  • ZmanZman

    Thank you for the prompt response. Here is my struggle to assign com ports for a remote Bluetooth device that I can discover and pair with through my C# application. My C# is a simple application that discovers and pair Bluetooth devices, also it's supposed to let user know that these are the Com Port assigned to this device (like the Windows Bluetooth device manager does. When you add a Bluetooth device using the Windows Bluetooth Devices you can see the Com ports  assigned to the device). In my application, I can discover BT device as I've mentioned before, I can find the device address and serial port service; but now I need to assign com ports. Using the GetPortNames() methods I can get serial port names, but it seems to me that it(GetPortNames()) does  not show all the ports that are in use. Anyway, so my issues are (1) how do I determine the com ports that are available for a BT device and (2) how can I assign those ports to the device so that data transfer can take place using the port. Thank  you again and appreciate any help on. My contact is hasan_z@hotmail.com

  • Clint RutkasClint I'm a "developer"

    @Benard, sorry man, I don't have a iPhone to test with.  Based on the quick glance at the article, if it mounts on Windows as a phone, the code *should* see it.  If not, something may have to be altered.

  • BernardBernard

    A little more detail. When I try to connect to any of those 8 services I get:

    Unable to connect to service. A socket operation was attempted to an unreachable network

  • BernardBernard

    But it doesn't Smiley The Iphone does not support SPP Sad It has 8 services:

    PAN Network Access Profile - Network Access Point.��|

    Wireless iAP -

    AVRCP DeviceRemote Control Device - Remote Control Device

    Audio Source -

    Phonebook -

    IrMC Sync -

    Handsfree Gateway -

    - PnP Information

    I cant seem to use any of them like SPP to create the proximity functionality. Any ideas?

  • Clint RutkasClint I'm a "developer"

    @Bernard should work, an iphone is just another bluetooth device

  • BernardBernard

    Did you ever get a chance to try with an iphone?

  • Clint RutkasClint I'm a "developer"

    @Bernard like I stated before, I don't have an iPhone to test with.  I'm not sure what Windows sees when the iPhone mounts via bluetooth.  This would ultimately determine how I would change the program.

  • BernardBernard

    Since the Iphone does not have SPP, one cannot open a connection to the port and using that to "ping" for connectivity.

    What other services could be used for this type of functionality? I love the auto lock idea, but the iphone cannot do it as is, because it does not have SPP.

    Have any examples of connecting to any other services?

    Many thanks

  • BernardBernard

    The only service windows sees is "Wireless iAP". Any ideas on what I can do with that?

    Alternatively, any way to make the radio scan fast to see what devices are in range?

  • Clint RutkasClint I'm a "developer"

    @Bernard, it is has been a very long time since I've looked at that code, I hate to give this type of response but it is "As Is".

    Another different implementation may be needed as this uses the C4F Developer kit.

    I've never tried it but http://32feet.codeplex.com/ may do what you need

  • Dima ShawahnehDima Shawahneh

    Hello every one

    I am using c4f devkit to discover all bluetooth devices within its range .. the problem is that it discovers all the devices including the paired devices even though the bluetooth is off on the mobile and this is a problem >>>

    Is there any way to check if this device paired or not and to check if it is really found and on ? .. plz help and great thanks.

  • Clint RutkasClint I'm a "developer"

    @Dima Shawahneh how are you keeping track of your bluetooth devices?  If the device bluetooth is off, there is no way to see it.

Remove this comment

Remove this thread


Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.