gpt4 book ai didi

c# - DeviceInformation PairAsync 在 WPF 中不起作用

转载 作者:行者123 更新时间:2023-11-30 13:54:12 27 4
gpt4 key购买 nike

我正在 WPF 应用程序中使用以下代码进行配对测试,但它始终失败并显示 Failed 状态。

为了使用 BluetoothLe 库,我刚刚添加了引用 (C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd)

if (!DeviceInformation.Pairing.IsPaired)
{
Logger.Info($"{DeviceInformation.Name} Try Pairing");
var result = await DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);

Logger.Info($"{result.Status}");
}

奇怪的是

  1. 使用相同的代码可以与 UWP App 配对。

  2. 取消配对在 UWP 和 WPF 应用程序中都可以。

  3. 不同的是,UWP 应用程序总是弹出系统对话框来确认配对和取消配对,而 WPF 应用程序不显示任何对话框。

谁能帮帮我?

解决了!谢谢。我刚刚使用了自定义配对。

public async void Pair()
{
if (!DeviceInformation.Pairing.IsPaired)
{
Logger.Info($"{DeviceInformation.Name} Try Pairing");
DeviceInformation.Pairing.Custom.PairingRequested += CustomOnPairingRequested;

var result = await DeviceInformation.Pairing.Custom.PairAsync(
DevicePairingKinds.ConfirmOnly, DevicePairingProtectionLevel.None);
DeviceInformation.Pairing.Custom.PairingRequested -= CustomOnPairingRequested;

Logger.Info($"{result.Status}");
}

}


private void CustomOnPairingRequested(
DeviceInformationCustomPairing sender,
DevicePairingRequestedEventArgs args)
{
Logger.Info("Test");
args.Accept();
}

最佳答案

如前所述here MS 人员表示,非 UWP 程序(如桌面和控制台应用程序)不正式支持应用内配对。然而,正如 Peter Torr 所暗示的那样,您可以“尝试通过 DeviceInformationCustomPairing 自己进行配对”。

这段代码对我有用;但是,仅适用于 DevicePairingKinds.ConfirmOnlyDevicePairingKinds.ProvidePin(其他选项会导致 RequiredHandlerNotRegistered 错误,但没有其他处理程序可以已注册。):

DeviceInformationCustomPairing p = DeviceInformation.Pairing.Custom;
p.PairingRequested += PairingRequestedHandler;
var pairingResult = await p.PairAsync(DevicePairingKinds.ConfirmOnly);
//or:
//var pairingResult = await p.PairAsync(DevicePairingKinds.ProvidePin);

处理程序可以从 official samples 中获取,或者您使用这个非常简化的版本:

private static void PairingRequestedHandler(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
{
switch (args.PairingKind)
{
case DevicePairingKinds.ConfirmOnly:
// Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
// If this is an App for 'Windows IoT Core' or a Desktop and Console application
// where there is no Windows Consent UX, you may want to provide your own confirmation.
args.Accept();
break;

case DevicePairingKinds.ProvidePin:
// A PIN may be shown on the target device and the user needs to enter the matching PIN on
// this Windows device. Get a deferral so we can perform the async request to the user.
var collectPinDeferral = args.GetDeferral();
string pinFromUser = "952693";
if (!string.IsNullOrEmpty(pinFromUser))
{
args.Accept(pinFromUser);
}
collectPinDeferral.Complete();
break;
}
}

常量变量 pinFromUser 只是一个例子。显然必须向用户请求!

关于c# - DeviceInformation PairAsync 在 WPF 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45191412/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com