相机条形码扫描仪入门Getting started with a camera barcode scanner

此处使用的代码段仅用于演示目的。The snippets used here are for demonstration purposes only. 有关工作示例,请参阅 条形码扫描器示例For a working sample, see the Barcode scanner sample.

步骤 1:向应用清单中添加功能声明Step 1: Add capability declarations to your app manifest

  1. 在 Microsoft Visual Studio 的 解决方案资源管理器中,双击 " appxmanifest.xml " 项,打开应用程序清单的设计器。In Microsoft Visual Studio, in Solution Explorer, open the designer for the application manifest by double-clicking the package.appxmanifest item.
  2. 选择 " 功能 " 选项卡Select the Capabilities tab
  3. 选中网络摄像头PointOfService 对应的框Check the boxes for Webcam and PointOfService

备注

软件解码器从相机接收要解码的帧并从你的应用程序提供预览时需要使用网络摄像头功能The Webcam capability is required to for the software decoder to receive frames from the camera to decode as well as to provide a preview from your application

步骤 2:添加 using 指令Step 2: Add using directives

using Windows.Devices.Enumeration;
using Windows.Devices.PointOfService;

步骤 3:定义设备选择器Step 3: Define your device selector

选项 A:找到所有条形码扫描仪Option A: Find all barcode scanners

string selector = BarcodeScanner.GetDeviceSelector();

选项 B:根据连接类型限定设备选择器的范围Option B: Scoping device selector to connection type

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

步骤4:枚举所有条形码扫描器Step 4: Enumerate all barcode scanners

如果你不希望在应用程序的生命周期内更改设备的列表,则可以使用 DeviceInformation枚举快照一次,但如果你认为条码扫描器列表可能会在应用程序的生存期内发生更改,则应改用 DeviceWatcherIf you do not expect the list of devices to change over the lifespan of your application you can enumerate a snapshot just once with DeviceInformation.FindAllAsync, but if you believe that the list of barcode scanners could change over the lifespan of your application you should use a DeviceWatcher instead.

重要

使用 GetDefaultAsync 枚举 PointOfService 设备可能导致不一致的行为,因为它只返回在类中找到的第一个设备,这可能随会话的变化而改变。Using GetDefaultAsync to enumerate PointOfService devices can result in inconsistent behavior as it simply returns the first device found in the class and this can change from session to session.

选项 A:枚举条形码扫描仪的快照Option A: Enumerate a snapshot of barcode scanners

DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(selector);

提示

请参阅枚举设备快照了解有关使用 FindAllAsync 的详细信息。See Enumerate a snapshot of devices for more information on using FindAllAsync.

选项 B:枚举可用的条形码扫描器并监视对可用扫描仪的更改Option B: Enumerate available barcode scanners and watch for changes to the available scanners

DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(selector);
watcher.Added += Watcher_Added;
watcher.Removed += Watcher_Removed;
watcher.Updated += Watcher_Updated;
watcher.Start();

提示

请参阅枚举和观察设备更改DeviceWatcher 了解详细信息。See Enumerate and watch device changes and DeviceWatcher for more information.

步骤 5:识别相机条形码扫描仪Step 5: Identify camera barcode scanners

相机条形码扫描仪在 Windows 将连接到计算机的相机与软件解码器配对时动态创建。A camera barcode scanner is created dynamically as Windows pairs the camera(s) attached to your computer with a software decoder. 每个相机 - 解码器对都是一个功能完全的条形码扫描仪。Each camera - decoder pair is a fully functional barcode scanner.

对于生成的设备集合中的每个条形码扫描器,可以通过检查 BarcodeScanner. VideoDeviceID 属性来区分照相机条形码扫描器和物理条形码扫描仪。For each barcode scanner in the resulting device collection, you can differentiate between camera barcode scanners and physical barcode scanners by checking the BarcodeScanner.VideoDeviceID property. 非 NULL VideoDeviceID 表示设备集合中的条形码扫描器对象是相机条形码扫描器。A non-NULL VideoDeviceID indicates that the barcode scanner object from your device collection is a camera barcode scanner. 如果有多个相机条形码扫描器,你可能想要生成一个不包括物理条形码扫描器的单独集合。If you have more than one camera barcode scanner you might want to build a separate collection which excludes physical barcode scanners.

使用随 Windows 附带的解码器的相机条形码扫描器标识为:Camera barcode scanners using the decoder that ships with Windows are identified as:

Microsoft BarcodeScanner(你的相机名称在这里Microsoft BarcodeScanner (name of your camera here)

如果有多个照相机并且它们内置于计算机的机箱中,则该名称可能会区分 两个照相机。If you have more than one camera, and they are built into the chassis of your computer, the name might differentiate between front and rear cameras.

备注

将来可能会发布具有不同命名方案的其他软件解码器。In the future, additional software decoders with different naming schemes might be released.

当 DeviceWatcher 开始 (步骤 4) 时,它将在每个连接的设备上进行枚举。When the DeviceWatcher starts (step 4), it enumerates through each connected device. 此处,我们将可用的扫描仪添加到条形码扫描器集合,并将该集合绑定到 ListBox。Here we add the available scanners to a barcode scanner collection and bind the collection to a ListBox.

ObservableCollection<BarcodeScannerInfo> barcodeScanners = new ObservableCollection<BarcodeScannerInfo>();

private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        barcodeScanners.Add(new BarcodeScannerInfo(args.Name, args.Id));

        // Select the first scanner by default.
        if (barcodeScanners.Count == 1)
        {
            ScannerListBox.SelectedIndex = 0;
        }
    });
}

当列表框的 SelectedIndex 更改 (默认情况下) 上一个代码段中选中第一项时,将查询设备信息。When the SelectedIndex of the ListBox changes (the first item is selected by default in the previous snippet), we query the device info.

private async void ScannerSelection_Changed(object sender, SelectionChangedEventArgs args)
{
    var selectedScannerInfo = (BarcodeScannerInfo)args.AddedItems[0];
    var deviceId = selectedScannerInfo.DeviceId;

    await SelectScannerAsync(deviceId);
}

步骤 6:认领相机条形码扫描仪Step 6: Claim the camera barcode scanner

使用 BarcodeScanner.ClaimScannerAsync 来获取对相机条形码扫描仪的独占使用。Use BarcodeScanner.ClaimScannerAsync to obtain exclusive use of the camera barcode scanner.

private async Task SelectScannerAsync(string scannerDeviceId)
{
    selectedScanner = await BarcodeScanner.FromIdAsync(scannerDeviceId);

    if (selectedScanner != null)
    {
        claimedScanner = await selectedScanner.ClaimScannerAsync();
        if (claimedScanner != null)
        {
            await claimedScanner.EnableAsync();
        }
        else
        {
            rootPage.NotifyUser("Failed to claim the selected barcode scanner", NotifyType.ErrorMessage);
        }
    }
    else
    {
        rootPage.NotifyUser("Failed to create a barcode scanner object", NotifyType.ErrorMessage);
    }
}

步骤 7:系统提供的预览Step 7: System provided preview

用户要成功扫描相机的条形码需要使用相机预览。A camera preview is needed for the user to successfully aim the camera at barcodes. Windows 提供了一个简单的相机预览,用于启动用于基本控制相机条形码扫描器的对话框。Windows provides a simple camera preview that launches a dialog for basic control of the camera barcode scanner. 调用 ClaimedBarcodeScanner.ShowVideoPreview 即可打开对话框,完成后调用 ClaimedBarcodeScanner.HideVideoPreview 将其关闭。Simply call ClaimedBarcodeScanner.ShowVideoPreview to open the dialog and ClaimedBarcodeScanner.HideVideoPreview to close it when finished.

提示

请参阅托管预览了解如何托管应用程序中相机条形码扫描仪的预览。See Hosting Preview to host the preview for camera barcode scanner in your application.

步骤8:启动扫描Step 8: Initiate scan

你可以通过调用 StartSoftwareTriggerAsync 来启动扫描过程。You can initiate the scan process by calling StartSoftwareTriggerAsync.

根据 IsDisabledOnDataReceived 的值,扫描程序可能只扫描一个条形码,然后在调用 StopSoftwareTriggerAsync之前停止或扫描。Depending on the value of IsDisabledOnDataReceived the scanner might scan only one barcode then stop or scan continuously until you call StopSoftwareTriggerAsync.

设置所需的 IsDisabledOnDataReceived 值来在解码条形码时控制扫描仪行为。Set the desired value of IsDisabledOnDataReceived to control the scanner behavior when a barcode is decoded.

Value 描述Description
TrueTrue 在扫描一个条形码后停止Scan only one barcode then stop
FalseFalse 持续扫描条形码而不停止Continuously scan barcodes without stopping

另请参阅See also

示例Samples