開始使用相機條碼掃描器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:將功能宣告加入至 App 資訊清單Step 1: Add capability declarations to your app manifest

  1. 在 Microsoft Visual Studio 的 方案總管中,按兩下 package.appxmanifest 專案以開啟應用程式資訊清單的設計工具。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:新增使用指示詞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();

提示

如需詳細資訊,請參閱列舉及監看裝置變更DeviceWatcherSee 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;
        }
    });
}

當 ListBox 的 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