AppleSeeker's Tech Blog
Welcome to AppleSeeker's space

本文主要讲述如何打开,关闭蓝牙。在后续文章中会讲述如何利用蓝牙实现文件传输等。

由于WM模拟器不支持蓝牙的调试,所以,如果你要调试代码,请在实际真实的设备中调试。

打开/关闭蓝牙主要依赖1个API(BthUtil.dll中的BthSetMode,传入蓝牙模式)

蓝牙共3个模式:
PowerOff关闭蓝牙/Connectable打开蓝牙/Discoverable打开蓝牙并可发现。
Connectable和Discoverable的区别:
Connectable:蓝牙虽开启,但对于比它晚开启的蓝牙设备,是无法发现的。
Discoverable:蓝牙开启,并能被别的设备所发现。

主要代码:

 1 BluetoothMode mode;
 2 
 3 switch (this.comboBox1.SelectedIndex)
 4 {
 5     case 0:
 6         mode = BluetoothMode.PowerOff;
 7         break;
 8     case 1:
 9         mode = BluetoothMode.Connectable;
10         break;
11     case 2:
12         mode = BluetoothMode.Discoverable;
13         break;
14     default:
15         mode = BluetoothMode.PowerOff;
16         break;
17 }
18 
19 int result = BthSetMode(mode);
20 if (result != 0)
21     MessageBox.Show(string.Format("Error : {0}", Marshal.GetLastWin32Error().ToString()));
22 else
23     GetBluetoothStatue();

API的定义

1         [DllImport("BthUtil.dll", SetLastError = true)]
2         public static extern int BthSetMode(BluetoothMode dwMode);
3 
4         [DllImport("BthUtil.dll", SetLastError = true)]
5         public static extern int BthGetMode(out BluetoothMode dwMode);

 

到此,一个简单的蓝牙设备控制器就算实现了。Demo比较简单,给入门的开发者以启示。

代码下载:DeviceBluetoothDemo.rar

Author:Appleseeker
Date:2008-09-15

posted on 2008-09-15 17:46  AppleSeeker(冯峰)  阅读(3288)  评论(8编辑  收藏  举报