在预览窗口关闭时禁用条形码扫描仪

时间:2019-04-16 14:25:33

标签: c# uwp barcode-scanner

当我关闭BarcodeScanner的预览窗口时,网络摄像头保持活动状态,我想防止这种情况发生,因为看到相机仍在打开并且即使我仍然可以扫描一些条形码,这有点奇怪关闭预览。

关闭预览窗口时,我不知道如何禁用BarcodeScanner

这是我的“ BarcodeScanner”代码:

private async Task<bool> ClaimScanner()
{
    bool res = false;

    string selector = BarcodeScanner.GetDeviceSelector();
    DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(selector);

    if(scanner == null)
        scanner = await BarcodeScanner.FromIdAsync(deviceCollection[0].Id);

    if (scanner != null)
    {
        if(claimedBarcodeScanner == null)
            claimedBarcodeScanner = await scanner.ClaimScannerAsync();

        if (claimedBarcodeScanner != null)
        {
            claimedBarcodeScanner.DataReceived += ClaimedBarcodeScanner_DataReceivedAsync;
            claimedBarcodeScanner.ReleaseDeviceRequested += ClaimedBarcodeScanner_ReleaseDeviceRequested;
            claimedBarcodeScanner.IsDecodeDataEnabled = true;
            claimedBarcodeScanner.IsDisabledOnDataReceived = true;
            await claimedBarcodeScanner.EnableAsync();

            res = true;
            Debug.WriteLine("Barcode Scanner claimed");
        }
    }
    antispam = false;
    return res;
}

public async void ScanBarcodeAsync()
{
    if(claimedBarcodeScanner == null && !antispam)
    {
        antispam = true;
        await ClaimScanner();
    }
    if(claimedBarcodeScanner != null)
    {
        await claimedBarcodeScanner.ShowVideoPreviewAsync();
        await claimedBarcodeScanner.StartSoftwareTriggerAsync();
        claimedBarcodeScanner = null;
    }
}

private async void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            if (currentDataContext != null && currentDataContext is Scannable)
            {
                Debug.WriteLine(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel));
                Scannable obj = (Scannable)currentDataContext;
                obj.NumSerie = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
            }
        }
    );
}

void ClaimedBarcodeScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
{
    // always retain the device
    e.RetainDevice();
}

编辑:我使用了Digimarc提供的Microsoft指示的库:https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/pos-camerabarcode

1 个答案:

答案 0 :(得分:1)

  

在预览窗口关闭时禁用条形码扫描器

ClaimedBarcodeScanner具有StopSoftwareTriggerAsync方法,如果要在关闭预览窗口时禁用条形码扫描器,只需在HideVideoPreview之后调用StopSoftwareTriggerAsync方法。

private async void HidePreviewButton_Click(object sender, RoutedEventArgs e)
{
    claimedScanner?.HideVideoPreview();
    await claimedScanner?.StopSoftwareTriggerAsync();   
}