CardAdded功能未在UWP应用中触发

时间:2016-04-08 09:24:33

标签: c# win-universal-app

我有一个UWP应用程序,通过用户名和密码以及读卡器执行登录。 那是我的代码。

public sealed partial class MainPage : Page
{
    private SynchronizationContext uiContext = null;

    public MainPage()
    {
        this.InitializeComponent();
        getMenu();

        uiContext = SynchronizationContext.Current;
        smartCard();
    }

    private async void smartCard()
    {
        string selector = SmartCardReader.GetDeviceSelector();
        DeviceInformationCollection devices =
            await DeviceInformation.FindAllAsync(selector);

        foreach (DeviceInformation device in devices)
        {
            SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);
            reader.CardAdded += Reader_CardAdded;
        }
    }

    private void Reader_CardAdded(object sender, CardAddedEventArgs args)
    {
        try
        {
            SmartCardReader send = (SmartCardReader)sender;
            // some stuff
            Debug.WriteLine(send.DeviceId);
            // A card has been inserted into the sender SmartCardReader.
        }
        catch (Exception e)
        {
            Debug.WriteLine("CardAdded Exception: " + e.Message);
        }
    }

每次我的读卡器读取卡片时,它只会在聚焦文本框中打印卡片代码,而不执行相关的cardAdded功能。一旦卡片进入读卡器,我真的需要触发功能。 有什么建议我做错了吗?

1 个答案:

答案 0 :(得分:0)

这一行: SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);是丘比特。它创建一个本地范围变量,一旦离开本地foreach范围,将删除事件处理程序。将SmartCardReader reader移至类范围将为您解决问题。