Create a barcode scanner application

7/17/2014

This topic shows how to create a barcode scanner application, claim it for exclusive use, enable it to receive data, and read a barcode. This sample uses the Windows.Devices.PointOfService API.

Implementing a barcode scanner

In preparation for this walkthrough, download the sample. This sample demonstrates these tasks:

  1. Create the barcode scanner
  2. Claim the barcode scanner for exclusive use
  3. Add event handlers
  4. Build and run the sample

The app package manifest file must specify the device capability name for Point of Service (POS) devices. All POS apps are required to declare DeviceCapability in the app package manifest, either by using "PointofService" or by using a device specific GUID, such as "C243FFBD-3AFC-45E9-B3D3-2BA18BC7EBC5" for a barcode scanner.

Important

At this time, the Visual Studio 2013 designer does not provide a checkbox for including this capability in the app package manifest. You need to manually include the POS capability in your manifest file. To learn how, see this link.

The following list shows the barcode scanners that were used with this sample:

  • Honeywell 1900GSR-2
  • Honeywell 1200g-2
  • Intermec SG20

In addition to the devices listed, you can use barcode scanners from various manufacturers that adhere to the USB HID POS Scanner specification.

Create the barcode scanner

The first step in any bardcode scanner app is to create a bardcode scanner instance. Call the GetDefaultAsync method to get the first available barcode scanner. The following code snippet demonstrates how to do this:

// Create the default barcode scanner
// Returns true if the barcode scanner is created; Otherwise returns false 
private async Task<bool> CreateDefaultScannerObject() 
{ 
   if (scanner == null) 
   { 
      UpdateOutput("Creating Barcode Scanner object."); 
      scanner = await BarcodeScanner.GetDefaultAsync(); 

      if (scanner != null) 
      { 
         UpdateOutput("Default Barcode Scanner created."); 
         UpdateOutput("Device Id is:" + scanner.DeviceId); 
      } 
      else 
      { 
         UpdateOutput("Barcode Scanner not found. Please connect a Barcode Scanner."); 
         return false; 
      } 
   } 
   return true; 
}

Claim and enable the barcode scanner

The next thing you will normally do is call the ClaimScannerAsync method to claim the device for exclusive use. Then, enable the barcode scanner by calling the EnableAsync method of the claimed device. The following code snippet demonstrates both steps:

// Claim the barcode scanner  
// Returns true if claim is successful; otherwise returns false 
private async Task<bool> ClaimScanner() 
{ 
   if (claimedScanner == null) 
   { 
      // claim the barcode scanner 
      claimedScanner = await scanner.ClaimScannerAsync(); 

      // enable the claimed barcode scanner 
      if (claimedScanner != null) 
      { 
         UpdateOutput("Claim Barcode Scanner succeeded."); 
      } 
      else 
      { 
         UpdateOutput("Claim Barcode Scanner failed."); 
         return false; 
      } 
   } 
   return true; 
}

// Enable the claimed barcode scanner
// Returns true if the barcade scanner is successfully enabled; otherwise, false 
private async Task<bool> EnableScanner() 
{
   if (claimedScanner == null) 
   { 
      return false;
   } 
   else 
   { 
      await claimedScanner.EnableAsync(); 

      UpdateOutput("Enable Barcode Scanner succeeded."); 

      return true; 
   }
}

Add event handlers

Barcode scanner applications use two important event handlers, DataReceived and ReleaseDeviceRequested.

The DataReceived event occurs when the device scans a barcode and allows your app to receive and process the scanned data. Its The args parameter contains the BarcodeScannerReport, which in turn contains the data obtained from the scan. The following code snippet demonstrates how to use this event:

// The event handler for the DataReceived event is fired when a barcode is scanned by the barcode scanner
async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) 
{
   // Update the UI in the sample app with the data received from the scan 
   await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
   {
      // Read the data from the buffer and convert to string
      ScenarioOutputScanDataLabel.Text = GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);

      ScenarioOutputScanData.Text = GetDataString(args.Report.ScanData);

      ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
   });
}

The ReleaseDeviceRequested event occurs when the device gets a request to release its exclusive claim. When an application gets a request to release its exclusive claim to the barcode scanner, it must handle the request by retaining the device; otherwise, it will lose its claim. The second scenario in this sample shows the release and retain functionality. The event handler for ReleaseDeviceRequested shows how retain the device:

/// This method is called when a claim request is made on instance 2. If a retain request was placed on the device it rejects the new claim.
async void claimedBarcodeScannerInstance2_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) 
{
   await MainPage.Current.Dispatcher.RunAsync( 
      Windows.UI.Core.CoreDispatcherPriority.Normal, 
      () => 
      { 
         UpdateOutput(String.Format("\nReleaseDeviceRequested ({0})", claimedBarcodeScannerInstance2.DeviceId)); 
         // Check if the instance wants to retain the device 
         if (Retain2.IsChecked == true) 
         { 
            try 
            { 
               // Retain the device 
               claimedBarcodeScannerInstance2.RetainDevice(); 
               UpdateOutput(String.Format("\t(Scanner Retained)")); 
            } 
            catch (Exception exception) 
            { 
               UpdateOutput(String.Format("\t(retain failed) ({0})", exception.ToString())); 
            } 
         }
         // Release the device 
         else  
         {
               claimedBarcodeScannerInstance2.Dispose(); 
               claimedBarcodeScannerInstance2 = null; 
               UpdateOutput("Scanner Released."); 
         }
      } 
   ); 
}

Build and run the sample

Build the sample by following these steps:

  1. Start Visual Studio 2013 and select File > Open > Project/Solution.
  2. Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio 2013 Solution (.sln) file.
  3. Press F7 or use Build > Build Solution to build the sample.

After the solution has been successfully built, you can run and debug the app by pressing F5 or use Debug > Start Debugging. To run the app without debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

See Also

Concepts

Develop Applications (Handheld 8.1)