private async void Connect_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(App.ChatServiceID)); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect()); if (dev != null) { remoteService = await RfcommDeviceService.FromIdAsync(dev.Id); if (remoteService != null) { InputText.IsEnabled = true; } } }
private async void Button_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect(200, 20, 50, 50)); if (dev != null) { // if a device is selected create a BluetoothDevice instance to get more information RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id); if (service != null) { foreach (KeyValuePair <uint, IBuffer> attrib in await service.GetSdpRawAttributesAsync()) { SdpDataElement de = SdpDataElement.FromByteArray(attrib.Value.ToArray()); System.Diagnostics.Debug.WriteLine(attrib.Key.ToString("X") + " " + de.ToString()); } // set data-binding so that device properties are displayed DeviceInformationPanel.DataContext = service; } } }
/// <summary> /// Click handler for camera button. Spawns device picker UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void UICameraButton_Click(object sender, RoutedEventArgs e) { // Disable the top menu while handling the click await UpdateMediaSourceButtonsAsync(false); var devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = UICameraButton.TransformToVisual(null); Windows.Foundation.Point point = ge.TransformPoint(new Windows.Foundation.Point()); Windows.Foundation.Rect rect = new Windows.Foundation.Rect(point, new Windows.Foundation.Point(point.X + UICameraButton.ActualWidth, point.Y + UICameraButton.ActualHeight)); DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (di != null) { try { NotifyUser("Attaching to camera " + di.Name); await ConfigureFrameSourceAsync(di, m_inputImageFeatureDescriptor); } catch (Exception ex) { NotifyUser("Error occurred while initializating MediaCapture:\n" + ex.Message); } } // Re-enable the top menu once done handling the click await UpdateMediaSourceButtonsAsync(true); }
public static IAsyncOperation <DeviceInformation> PickSingleDeviceAsync() { if (!(Window.Current.Content is Frame rootFrame)) { throw new ArgumentException(nameof(rootFrame)); } var devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); return(devicePicker.PickSingleDeviceAsync(rootFrame.GetPickerRect())); }
private async Task <BluetoothDeviceInfo> DoPickSingleDeviceAsync() { Rect bounds = Rect.Empty; var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDeviceInfo(device)); }
private async void Button1_Click(object sender, EventArgs e) { var picker = new DevicePicker(); picker.DeviceSelected += Picker_DeviceSelected; picker.Filter.SupportedDeviceSelectors.Add( BluetoothDevice.GetDeviceSelectorFromPairingState(false)); // sync // picker.Show(new Windows.Foundation.Rect(100, 100, 500, 500)); // async DeviceInformation di = await picker.PickSingleDeviceAsync(new Windows.Foundation.Rect(0, 0, 0, 0), Windows.UI.Popups.Placement.Default); if (di == null) { return; } if (di.Pairing.IsPaired == false) { di.Pairing.Custom.PairingRequested += Custom_PairingRequested; if (di.Pairing.CanPair == true) { var pairResult = await di.Pairing.PairAsync(); if (pairResult.Status == DevicePairingResultStatus.Paired) { // do something } } else { var pairResult = await di.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin); if (pairResult.Status == DevicePairingResultStatus.Paired) { // do something } } } }
/// <summary> /// Click handler for camera button. Spawns device picker UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void CameraButton_Click(object sender, RoutedEventArgs e) { // Disable the top menu while handling the click await UpdateMediaSourceButtonsAsync(false); var devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = UICameraButton.TransformToVisual(null); Windows.Foundation.Point point = ge.TransformPoint(new Windows.Foundation.Point()); Windows.Foundation.Rect rect = new Windows.Foundation.Rect(point, new Windows.Foundation.Point(point.X + UICameraButton.ActualWidth, point.Y + UICameraButton.ActualHeight)); DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (di != null) { try { NotifyUser("Attaching to camera " + di.Name); // Create new MediaCapture connected to our device var mediaCapture = new MediaCapture(); var settings = new MediaCaptureInitializationSettings { MemoryPreference = MediaCaptureMemoryPreference.Auto, StreamingCaptureMode = StreamingCaptureMode.Video, VideoDeviceId = di.Id, }; await mediaCapture.InitializeAsync(settings); await ConfigureFrameSourceAsync(mediaCapture); } catch (Exception ex) { NotifyUser("Error occurred while initializating MediaCapture:\n" + ex.Message); } } // Re-enable the top menu once done handling the click await UpdateMediaSourceButtonsAsync(true); }
async Task <BluetoothDevice> DoRequestDevice(RequestDeviceOptions options) { DevicePicker picker = new DevicePicker(); picker.Appearance.AccentColor = Windows.UI.Color.FromArgb(0xff, 0xff, 0xff, 0xff); picker.Appearance.ForegroundColor = Windows.UI.Color.FromArgb(0xff, 0xff, 0xff, 0xff); picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; if (!options.AcceptAllDevices) { foreach (var filter in options.Filters) { if (!string.IsNullOrEmpty(filter.Name)) { picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name)); } foreach (var service in filter.Services) { picker.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid(service)); } } } if (picker.Filter.SupportedDeviceSelectors.Count == 0) { //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelector()); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); } var deviceInfo = await picker.PickSingleDeviceAsync(Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds); if (deviceInfo == null) { return(null); } var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); return(new BluetoothDevice(device)); }
async void FindPrinter_Click() { isBusy = true; UpdateButtons(); rootPage.NotifyUser("", NotifyType.StatusMessage); rootPage.ReleaseAllPrinters(); // Select a PosPrinter device using the Device Picker. DevicePicker devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceSelectors.Add(PosPrinter.GetDeviceSelector()); // Anchor the picker on the Find button. GeneralTransform ge = FindButton.TransformToVisual(Window.Current.Content as UIElement); Rect rect = ge.TransformBounds(new Rect(0, 0, FindButton.ActualWidth, FindButton.ActualHeight)); DeviceInformation deviceInfo = await devicePicker.PickSingleDeviceAsync(rect); rootPage.deviceInfo = deviceInfo; PosPrinter printer = null; if (deviceInfo != null) { printer = await PosPrinter.FromIdAsync(deviceInfo.Id); } if (printer != null && printer.Capabilities.Receipt.IsPrinterPresent) { rootPage.Printer = printer; rootPage.NotifyUser("Found receipt printer.", NotifyType.StatusMessage); } else { // Get rid of the printer we can't use. printer?.Dispose(); rootPage.NotifyUser("Please select a device whose printer is present.", NotifyType.ErrorMessage); } isBusy = false; UpdateButtons(); }
/// <summary> /// Handle user selection of a camera as frame source /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void CameraButton_Click(object sender, RoutedEventArgs e) { // Disable the top menu while handling the click await UpdateMediaSourceButtonsAsync(false); var devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = CameraButton.TransformToVisual(null); Point point = ge.TransformPoint(new Point()); Rect rect = new Rect(point, new Point(point.X + CameraButton.ActualWidth, point.Y + CameraButton.ActualHeight)); DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (di != null) { // Reset application state await m_lock.WaitAsync(); { m_bindings.Clear(); // Only need to clear bindings to stop skill executions } m_lock.Release(); try { NotifyUser("Attaching to camera " + di.Name, NotifyType.StatusMessage); await ConfigureFrameSourceAsync(di); } catch (Exception ex) { NotifyUser("Error occurred while initializating MediaCapture:\n" + ex.Message, NotifyType.ErrorMessage); } } // Re-enable the top menu once done handling the click await UpdateMediaSourceButtonsAsync(true); }
private async void ShowDevicePicker() { devicePicker = new DevicePicker(); // only show Bluetooth Low Energy devices devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = pickDeviceButton.TransformToVisual(null); Point point = ge.TransformPoint(new Point()); Rect rect = new Rect(point, new Point(point.X + pickDeviceButton.ActualWidth, point.Y + pickDeviceButton.ActualHeight)); DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (null != di) { ViewModel.GearVrController = new GearVrController(); await ViewModel.GearVrController.Create(di); } }
private async void ClickedMethod(object obj) { var devicePicker = new DevicePicker(); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); // Calculate the position to show the picker (right below the buttons) Button DiscoverButton = obj as Button; if (DiscoverButton != null) { var ge = DiscoverButton.TransformToVisual(null); var point = ge.TransformPoint(new Point()); var rect = new Rect(point, new Point(100, 100)); var device = await devicePicker.PickSingleDeviceAsync(rect); if (device != null) { var bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(device.Id); } } }
/// <summary> /// Sets the camera object to use, in case you don't want to use the default /// </summary> private async void SetCameraDevice(object sender, TappedRoutedEventArgs e) { // Create a DevicePicker var devicePicker = new DevicePicker(); // Set that we are looking for video capture devices devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture); // Calculate the position to show the picker (right below the buttons) GeneralTransform transform = SetCameraButton.TransformToVisual(null); Point point = transform.TransformPoint(new Point()); Rect rect = new Rect(point, new Point(point.X + SetCameraButton.ActualWidth, point.Y + SetCameraButton.ActualHeight)); // Use the device picker to pick the device DeviceInformation deviceInfo = await devicePicker.PickSingleDeviceAsync(rect); if (null != deviceInfo) { _presence.CameraDeviceId = deviceInfo.Id; _presence.IsDefaultCapture = false; } }
private async void Button_Click(object sender, RoutedEventArgs e) { string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush); DevicePicker picker = new DevicePicker(); picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33); picker.Appearance.ForegroundColor = Colors.White; picker.Appearance.AccentColor = Colors.Goldenrod; // add our query string picker.Filter.SupportedDeviceSelectors.Add(aqs); // prompt user to select a single device DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect()); if (dev != null) { // if a device is selected create a BluetoothDevice instance to get more information BluetoothDevice bd = await BluetoothDevice.FromIdAsync(dev.Id); foreach (IBuffer r in bd.SdpRecords) { if (r.Length > 0) { SdpDataElement record = SdpDataElement.FromByteArray(r.ToArray()); if (record.Value != null) { string s = record.ToString(); System.Diagnostics.Debug.WriteLine(s); } } } // set data-binding so that device properties are displayed DeviceInformationPanel.DataContext = bd; } }
private async void ShowDevicePicker(bool pickSingle) { showDevicePickerButton.IsEnabled = false; ResultCollection.Clear(); devicePicker = new DevicePicker(); // First get the device selector chosen by the UI. DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem; if (null == deviceSelectorInfo.Selector) { // If the a pre-canned device class selector was chosen, call the DeviceClass overload devicePicker.Filter.SupportedDeviceClasses.Add(deviceSelectorInfo.DeviceClassSelector); } else { // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call devicePicker.Filter.SupportedDeviceSelectors.Add(deviceSelectorInfo.Selector); } rootPage.NotifyUser("Showing Device Picker", NotifyType.StatusMessage); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = pickSingleDeviceButton.TransformToVisual(null); Point point = ge.TransformPoint(new Point()); Rect rect = new Rect(point, new Point(point.X + pickSingleDeviceButton.ActualWidth, point.Y + pickSingleDeviceButton.ActualHeight)); if (pickSingle) { DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (null != di) { ResultCollection.Add(new DeviceInformationDisplay(di)); } showDevicePickerButton.IsEnabled = true; } else { devicePicker.DevicePickerDismissed += new TypedEventHandler<DevicePicker, object>( async (picker, obj) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { showDevicePickerButton.IsEnabled = true; rootPage.NotifyUser("Hiding Device Picker", NotifyType.StatusMessage); }); }); devicePicker.DeviceSelected += new TypedEventHandler<DevicePicker, DeviceSelectedEventArgs>( async (picker, args) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { ResultCollection.Clear(); ResultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice)); }); }); // Show the picker devicePicker.Show(rect); } }
private async void ShowDevicePicker(bool pickSingle) { showDevicePickerButton.IsEnabled = false; resultCollection.Clear(); var devicePicker = new DevicePicker(); // First get the device selector chosen by the UI. DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem; if (null == deviceSelectorInfo.Selector) { // If the a pre-canned device class selector was chosen, call the DeviceClass overload devicePicker.Filter.SupportedDeviceClasses.Add(deviceSelectorInfo.DeviceClassSelector); } else { // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call devicePicker.Filter.SupportedDeviceSelectors.Add(deviceSelectorInfo.Selector); } rootPage.NotifyUser("Showing Device Picker", NotifyType.StatusMessage); // Calculate the position to show the picker (right below the buttons) GeneralTransform ge = pickSingleDeviceButton.TransformToVisual(null); Point point = ge.TransformPoint(new Point()); Rect rect = new Rect(point, new Point(point.X + pickSingleDeviceButton.ActualWidth, point.Y + pickSingleDeviceButton.ActualHeight)); if (pickSingle) { DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect); if (null != di) { resultCollection.Add(new DeviceInformationDisplay(di)); } showDevicePickerButton.IsEnabled = true; } else { devicePicker.DevicePickerDismissed += new TypedEventHandler <DevicePicker, object>( async(picker, obj) => { // Must access UI elements from the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { showDevicePickerButton.IsEnabled = true; rootPage.NotifyUser("Hiding Device Picker", NotifyType.StatusMessage); }); }); devicePicker.DeviceSelected += new TypedEventHandler <DevicePicker, DeviceSelectedEventArgs>( async(picker, args) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { resultCollection.Clear(); resultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice)); }); }); // Show the picker devicePicker.Show(rect); } }
private async void AppBarButton_Click_1(object sender, RoutedEventArgs e) { try { StoreServicesCustomEventLogger logger = StoreServicesCustomEventLogger.GetDefault(); logger.Log("AddBluetooth"); string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher( BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), requestedProperties, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. // Added, Updated and Removed are required to get all nearby devices // deviceWatcher.Added += DeviceWatcher_Added; // deviceWatcher.Updated += DeviceWatcher_Updated; // deviceWatcher.Removed += DeviceWatcher_Removed; // EnumerationCompleted and Stopped are optional to implement. // deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; // deviceWatcher.Stopped += DeviceWatcher_Stopped; // Start the watcher. //deviceWatcher.Start(); var displayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); double ScreenWidth = 100; double ScreenHeight = 100; if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Portrait) { ScreenWidth = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); } if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Landscape) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } // For devices with software buttons instead hardware else if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } Rect rect = new Rect(new Point(ScreenHeight, ScreenWidth), new Point(100, 100)); DevicePicker devicePicker = new DevicePicker(); //devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); // devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); var s = await devicePicker.PickSingleDeviceAsync(rect); if (s != null) { var sd = await s.Pairing.PairAsync(); // await new MessageDialog(sd.ToString()+"\n"+ DevicePairingResultStatus.Paired).ShowAsync(); if (sd.Status == DevicePairingResultStatus.Paired || sd.Status == DevicePairingResultStatus.AlreadyPaired || sd.Status == DevicePairingResultStatus.AccessDenied) { //var rfcommServices = await ClassBluetoothDeviceSelect.bluetoothDeviced.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached); var bluetoothDevice = await BluetoothDevice.FromIdAsync(s.Id); Frame.Navigate(typeof(BlankPageBluettotchDevice), new ClassBluetoothDevice() { namea = s.Name, bluetoothDeviced = bluetoothDevice }); } } } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } }
public TionViewModel() { var picker = new DevicePicker(); picker.PickSingleDeviceAsync(); }
static async Task <BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options) { DevicePicker picker = new DevicePicker(); Rect bounds = Rect.Empty; //picker.Appearance.AccentColor = Windows.UI.Colors.Green; //picker.Appearance.ForegroundColor = Windows.UI.Colors.White; //picker.Appearance.BackgroundColor = Windows.UI.Colors.DarkGray; #if !UAP uint len = 64; byte[] buffer = new byte[len]; int hasPackage = GetCurrentPackageId(ref len, buffer); if (hasPackage == 0x3d54) { foreach (var attr in System.Reflection.Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute))) { picker.Appearance.Title = ((AssemblyProductAttribute)attr).Product + " wants to pair"; break; } } else { picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; } #else picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; bounds = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds; picker.Appearance.SelectedAccentColor = (Color)Windows.UI.Xaml.Application.Current.Resources["SystemAccentColor"]; #endif if (!options.AcceptAllDevices) { foreach (var filter in options.Filters) { if (!string.IsNullOrEmpty(filter.Name)) { picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name)); } foreach (var service in filter.Services) { picker.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid(service)); } } } if (picker.Filter.SupportedDeviceSelectors.Count == 0) { //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelector()); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); } var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDevice(device)); }
static async Task <BluetoothDevice> PlatformRequestDevice(RequestDeviceOptions options) { DevicePicker picker = new DevicePicker(); Rect bounds = Rect.Empty; #if !UAP uint len = 64; byte[] buffer = new byte[len]; IntPtr hwnd = IntPtr.Zero; try { // a console app will return a non-null string for title if (!string.IsNullOrEmpty(Console.Title)) { bounds = new Rect(0, 0, 480, 480); hwnd = GetConsoleWindow(); // set console host window as parent for picker ((IInitializeWithWindow)(object)picker).Initialize(hwnd); } } catch { } int hasPackage = GetCurrentPackageId(ref len, buffer); if (hasPackage == 0x3d54) { foreach (var attr in System.Reflection.Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute))) { picker.Appearance.Title = ((AssemblyProductAttribute)attr).Product + " wants to pair"; break; } } else { picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; } #else picker.Appearance.Title = Windows.ApplicationModel.Package.Current.DisplayName + " wants to pair"; bounds = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds; picker.Appearance.SelectedAccentColor = (Color)Windows.UI.Xaml.Application.Current.Resources["SystemAccentColor"]; #endif if (options != null && !options.AcceptAllDevices) { foreach (var filter in options.Filters) { if (!string.IsNullOrEmpty(filter.Name)) { picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromDeviceName(filter.Name)); } foreach (var service in filter.Services) { picker.Filter.SupportedDeviceSelectors.Add(GattDeviceService.GetDeviceSelectorFromUuid(service)); } } } if (picker.Filter.SupportedDeviceSelectors.Count == 0) { //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelector()); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); } try { var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDevice(device)); } catch (Exception ex) { if (ex.HResult == -2147023496) { throw new PlatformNotSupportedException("RequestDevice cannot be called from a Console application."); } return(null); } }