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

由于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

相关文章:

  • 2021-05-23
  • 2022-01-15
  • 2021-11-01
  • 2021-12-05
猜你喜欢
  • 2021-08-02
  • 2021-11-03
  • 2021-08-01
  • 2021-07-31
  • 2021-11-21
相关资源
相似解决方案