例子:Bluetooth app to device sample

本例子演示了:

  • 判断蓝牙是否打开,是通过一个HRsult值为0x8007048F的异常来判断的

catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
var result = MessageBox.Show(AppResources.Msg_BluetoothOff, "Bluetooth Off", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
ShowBluetoothcControlPanel();
}
}
  • 找到所有配对设备 - Windows.Networking.Proximity.PeerFinder

                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var peers = await PeerFinder.FindAllPeersAsync();
  • 尝试连接已配对设备

//从数据中获取已经选中的蓝牙设备,在ConnectToDevice方法中连接

            PairedDeviceInfo pdi = PairedDevicesList.SelectedItem as PairedDeviceInfo;
PeerInformation peer = pdi.PeerInfo; // Asynchronous call to connect to the device
ConnectToDevice(peer);

ConnectToDevice:

Windows.Networking.Sockets;

            try
{
Windows.Networking.Sockets.StreamSocket _socket = new StreamSocket();
string serviceName = (String.IsNullOrWhiteSpace(peer.ServiceName)) ? tbServiceName.Text : peer.ServiceName; // Note: If either parameter is null or empty, the call will throw an exception
await _socket.ConnectAsync(peer.HostName, serviceName); // If the connection was successful, the RemoteAddress field will be populated
MessageBox.Show(String.Format(AppResources.Msg_ConnectedTo, _socket.Information.RemoteAddress.DisplayName));
}
  • 当捕获蓝牙未打开的异常,后打开蓝牙设置页面:(Microsoft.Phone.Tasks)
        private void ShowBluetoothcControlPanel()
{
ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();
}
上一篇:第六节 etc/passwd 、etc/shadow 、 useradd 、 groupadd


下一篇:linux命令详解-useradd,groupadd