Wednesday, 9 July 2014

Windows Phone 8 Bar Code Scanner

To create Barcode Scanner in Windows phone 8 .It Developed with Zxing API .

Need to Add ZXing dll from here .
you may find zxing wp8.0 folder among that find zxing wp8.0 dll .

This dllm add to your Project .

and Enable the Camera to Device for this you find the  Properties folder in your solution  Properties/ WMAppManifest.xml /Click on the ID_CAP_CAMERA .

your MainPage.xaml is like below :-

<phone:PhoneApplicationPage
x:Class="ExBarcodeJuly9th.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent" Tap="LayoutRoot_Tap">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="350" />
            <RowDefinition Height="200" />
        </Grid.RowDefinitions>
        <Border Grid.Row="0" Background="CadetBlue"></Border>

            <Canvas x:Name="viewfinderCanvas" Grid.Row="1">

            <!--Camera viewfinder -->
            <Canvas.Background>
                <VideoBrush x:Name="viewfinderBrush">
                    <VideoBrush.RelativeTransform>
                        <CompositeTransform
                        x:Name="viewfinderTransform"
                        CenterX="0.5"
                        CenterY="0.5"
                        Rotation="90"/>
                    </VideoBrush.RelativeTransform>
                </VideoBrush>
            </Canvas.Background>
        </Canvas>
        <Grid Grid.Row="2" Background="CadetBlue">
            <Grid.RowDefinitions>
                <RowDefinition Height="100"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="250"/>
                <ColumnDefinition Width="250"/>
            </Grid.ColumnDefinitions>
         
            <Image Name="resulImage" Visibility="Collapsed" Margin="10,10,10,10" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" />
            <StackPanel Grid.Column="1" Grid.Row="1" Grid.RowSpan="2"  >
         
            <TextBlock x:Name="tbBarcodeType" Visibility="Collapsed" FontWeight="ExtraBold" />
            <TextBlock x:Name="tbBarcodeData" FontWeight="ExtraBold" TextWrapping="Wrap" />
        </StackPanel>
         
        </Grid>
     
    </Grid>
</phone:PhoneApplicationPage>


this Code below follows:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ExBarcodeJuly9th.Resources;
using ZXing;
using Microsoft.Devices;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace ExBarcodeJuly9th
{
    public partial class MainPage
    {
        private IBarcodeReader _barcodeReader;
        private PhotoCamera _phoneCamera;
        private WriteableBitmap _previewBuffer;
        private DispatcherTimer _scanTimer;
       static int MyID = 0;
        EventArgs eventarg;
        public MainPage()
        {
            InitializeComponent();
           
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            eventarg = e;
            _phoneCamera = new PhotoCamera();
            _phoneCamera.Initialized += Camera_Initialized;
            tbBarcodeType.Text = string.Empty;
            tbBarcodeData.Text = string.Empty;
            CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;


            viewfinderBrush.SetSource(_phoneCamera);


            _scanTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000f) };
            _scanTimer.Tick += (o, arg) => ScanForBarcode();
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            _scanTimer.Stop();


            if (_phoneCamera != null)
            {
                _phoneCamera.Dispose();
                _phoneCamera.Initialized -= Camera_Initialized;
                CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
            }
        }

        private void BcReader_ResultFound(Result obj)
        {

            if (!obj.Text.Equals(tbBarcodeData.Text))
            {
                VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
                tbBarcodeType.Text = obj.BarcodeFormat.ToString();
                tbBarcodeData.Text = obj.Text;

                _scanTimer.Stop();
                viewfinderCanvas.Visibility = Visibility.Collapsed;
                resulImage.Visibility = Visibility.Visible;
                resulImage.Source = _previewBuffer;
            }
        }

        private void Camera_Initialized(object sender, CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate
                {
                    _phoneCamera.FlashMode = FlashMode.On;

                    _previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height);

                    _barcodeReader = new BarcodeReader();


                    var supportedBarcodeFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.CODE_93, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8, BarcodeFormat.All_1D, BarcodeFormat.AZTEC, BarcodeFormat.CODABAR, BarcodeFormat.ITF, BarcodeFormat.MAXICODE, BarcodeFormat.MSI, BarcodeFormat.PDF_417, BarcodeFormat.PLESSEY, BarcodeFormat.RSS_14, BarcodeFormat.RSS_EXPANDED, BarcodeFormat.UPC_A, BarcodeFormat.UPC_E, BarcodeFormat .UPC_EAN_EXTENSION};
                    _barcodeReader.Options.PossibleFormats = supportedBarcodeFormats;

                    _barcodeReader.ResultFound += BcReader_ResultFound;
                    _scanTimer.Start();
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Unable to intilaize the Camera");
                });
            }
        }


        private void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
        {
            _phoneCamera.Focus();
        }

        private void ScanForBarcode()
        {

            //if (_phoneCamera.IsFocusSupported)
            //{
            //    _phoneCamera.Focus();
            //}

            _phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels);
            _previewBuffer.Invalidate();


            _barcodeReader.Decode(_previewBuffer);
        }

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //this.Dispatcher.BeginInvoke(() =>
            //{
             

            //    //Go back to the main page
            //    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

            //    //Don't allow to navigate back to the scanner with the back button
            //    NavigationService.RemoveBackEntry();
            //});

           // NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            NavigationService.Navigate(new Uri("/MainPage.xaml?ID=" + MyID, UriKind.Relative));
            MyID++;
            NavigationService.RemoveBackEntry();
        }
    }
}

No comments:

Post a Comment