Windows phone 8.1 Windows Phone 8.1:使用ZXing.Net扫描摄像头中的条形码

Windows phone 8.1 Windows Phone 8.1:使用ZXing.Net扫描摄像头中的条形码,windows-phone-8.1,barcode,zxing,barcode-scanner,Windows Phone 8.1,Barcode,Zxing,Barcode Scanner,我正在使用ZXing.Net库扫描/读取摄像机上的条形码。我使用了以下示例: 但它不起作用。它会冻结设备 如何在Windows Phone 8.1中使用ZXing.Net库?有什么例子吗? 还有其他可用的库吗?您需要先添加Zxing.Net库,然后在前端使用它 <phone:PhoneApplicationPage x:Class="BarCode.Scan" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation

我正在使用ZXing.Net库扫描/读取摄像机上的条形码。我使用了以下示例:

但它不起作用。它会冻结设备

如何在Windows Phone 8.1中使用ZXing.Net库?有什么例子吗?

还有其他可用的库吗?

您需要先添加Zxing.Net库,然后在前端使用它

<phone:PhoneApplicationPage
x:Class="BarCode.Scan"
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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />

    </Grid.RowDefinitions>

    <Canvas x:Name="viewfinderCanvas" Margin="0,0,0,10">

        <!--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>
        <TextBlock 
        x:Name="focusBrackets" 
        Text="[   ]" 
        FontSize="40" Visibility="Collapsed"/>
        <TextBlock Canvas.Left="129" TextWrapping="Wrap" Text="Tap to read the Barcode" Canvas.Top="721" Width="233" FontFamily="Segoe UI"/>
    </Canvas>
    <!--Used for debugging >-->
    <!--<StackPanel Grid.Row="1" Margin="20, 0">
        <TextBlock x:Name="tbBarcodeType" FontWeight="ExtraBold" />
        <TextBlock x:Name="tbBarcodeData" FontWeight="ExtraBold" TextWrapping="Wrap" />
    </StackPanel>-->
</Grid>

在后端使用这个

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 Microsoft.Devices;
using ZXing;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Input;

namespace BarCode
{
    public partial class Scan : PhoneApplicationPage
    {
        private PhotoCamera _phoneCamera;
        private IBarcodeReader _barcodeReader;
        private DispatcherTimer _scanTimer;
        private WriteableBitmap _previewBuffer;
        public Scan()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Initialize the camera object
            _phoneCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
            // _phoneCamera.Initialized += cam_Initialized;
            _phoneCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
            _phoneCamera.AutoFocusCompleted += _phoneCamera_AutoFocusCompleted;

            CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;

            //Display the camera feed in the UI
            viewfinderBrush.SetSource(_phoneCamera);


            // This timer will be used to scan the camera buffer every 250ms and scan for any barcodes
            _scanTimer = new DispatcherTimer();
            _scanTimer.Interval = TimeSpan.FromMilliseconds(250);
            _scanTimer.Tick += (o, arg) => ScanForBarcode();

            viewfinderCanvas.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(focus_Tapped);

            base.OnNavigatedTo(e);
        }


        void _phoneCamera_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate()
            {
                focusBrackets.Visibility = Visibility.Collapsed;
            });
        }

        void focus_Tapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                if (_phoneCamera != null)
                {
                    if (_phoneCamera.IsFocusAtPointSupported == true)
                    {
                        // Determine the location of the tap.
                        Point tapLocation = e.GetPosition(viewfinderCanvas);

                        // Position the focus brackets with the estimated offsets.
                        focusBrackets.SetValue(Canvas.LeftProperty, tapLocation.X - 30);
                        focusBrackets.SetValue(Canvas.TopProperty, tapLocation.Y - 28);

                        // Determine the focus point.
                        double focusXPercentage = tapLocation.X / viewfinderCanvas.ActualWidth;
                        double focusYPercentage = tapLocation.Y / viewfinderCanvas.ActualHeight;

                        // Show the focus brackets and focus at point.
                        focusBrackets.Visibility = Visibility.Visible;
                        _phoneCamera.FocusAtPoint(focusXPercentage, focusYPercentage);
                    }
                }
            }
            catch (Exception ex)
            {
                _phoneCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
            }
        }


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


        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            //we're navigating away from this page, we won't be scanning any barcodes
            _scanTimer.Stop();

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

        void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    _phoneCamera.FlashMode = FlashMode.Off;
                    _previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height);

                    _barcodeReader = new BarcodeReader();

                    // By default, BarcodeReader will scan every supported barcode type
                    // If we want to limit the type of barcodes our app can read, 
                    // we can do it by adding each format to this list object

                    //var supportedBarcodeFormats = new List<BarcodeFormat>();
                    //supportedBarcodeFormats.Add(BarcodeFormat.QR_CODE);
                    //supportedBarcodeFormats.Add(BarcodeFormat.DATA_MATRIX);
                    //_bcReader.PossibleFormats = supportedBarcodeFormats;

                    _barcodeReader.TryHarder = true;

                    _barcodeReader.ResultFound += _bcReader_ResultFound;
                    _scanTimer.Start();
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Unable to initialize the camera");
                });
            }
        }

        void _bcReader_ResultFound(Result obj)
        {
            // If a new barcode is found, vibrate the device and display the barcode details in the UI
            //if (!obj.Text.Equals(tbBarcodeData.Text))
            //{
                VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
                //tbBarcodeType.Text = obj.BarcodeFormat.ToString();
                //tbBarcodeData.Text = obj.Text;
                //NavigationService.Navigate(new Uri(string.Format("/AddCustomer.xaml?parameter={0}", Uri.EscapeUriString(obj.Text), UriKind.Relative)));
                PhoneApplicationService.Current.State["Text"] = obj.Text;   
            NavigationService.Navigate(new Uri("/PageYouWantToGetResult.xaml", UriKind.Relative));

        }

        private void ScanForBarcode()
        {
            //grab a camera snapshot
            _phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels);
            _previewBuffer.Invalidate();

            //scan the captured snapshot for barcodes
            //if a barcode is found, the ResultFound event will fire
            _barcodeReader.Decode(_previewBuffer);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageYouWantToNavigate.xaml", UriKind.Relative));
            base.OnBackKeyPress(e);

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Navigation;
使用Microsoft.Phone.Controls;
使用Microsoft.Phone.Shell;
使用微软设备;
使用ZXing;
使用System.Windows.Threading;
使用System.Windows.Media.Imaging;
使用System.Windows.Input;
名称空间条形码
{
公共部分类扫描:PhoneApplicationPage
{
私人照相/摄像机;
专用IBarcodeReader\u条形码阅读器;
私人调度员扫描计时器;
私有可写位图_previewBuffer;
公共扫描()
{
初始化组件();
}
受保护的覆盖无效OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//初始化摄影机对象
_phoneCamera=新的Microsoft.Devices.PhotoCamera(CameraType.Primary);
//_phoneCamera.Initialized+=cam_Initialized;
_phoneCamera.Initialized+=新事件处理程序(cam_Initialized);
_phoneCamera.AutoFocusCompleted+=\u phoneCamera\u AutoFocusCompleted;
CameraButtons.ShutterKeyHalfPressed+=CameraButtons\u ShutterKeyHalfPressed;
//在UI中显示摄影机提要
viewfinderBrush.SetSource(_phoneCamera);
//该计时器将用于每250ms扫描一次摄像头缓冲区,并扫描任何条形码
_scanTimer=新的调度程序();
_scanTimer.Interval=TimeSpan.From毫秒(250);
_scanTimer.Tick+=(o,arg)=>ScanForBarcode();
viewfinderCanvas.Tap+=新事件处理程序(焦点被点击);
基地。导航到(e);
}
无效\u电话摄像头\u自动对焦完成(对象发送器,摄像头操作完成事件参数e)
{
Deployment.Current.Dispatcher.BeginInvoke(委托()
{
Focus括号。可见性=可见性。折叠;
});
}
无效焦点(对象发送器,System.Windows.Input.GestureEventArgs e)
{
尝试
{
如果(_phoneCamera!=null)
{
if(_phoneCamera.IsFocusAtPointSupported==true)
{
//确定抽头的位置。
点tapLocation=e.GetPosition(viewfinderCanvas);
//定位带有估计偏移的焦点括号。
SetValue(Canvas.LeftProperty,tapLocation.X-30);
设置值(Canvas.TopProperty,tapLocation.Y-28);
//确定焦点。
双焦点xPercentage=tapLocation.X/viewfinderCanvas.ActualWidth;
双焦点ypercentage=tapLocation.Y/viewfinderCanvas.ActualHeight;
//显示焦点括号和焦点点。
焦点括号。可见性=可见性。可见;
_phoneCamera.FocusAtPoint(focusXPercentage,FocusTypercentage);
}
}
}
捕获(例外情况除外)
{
_phoneCamera.Initialized+=新事件处理程序(cam_Initialized);
}
}
void CameraButtons\u ShutterKeyHalf Pressed(对象发送器,事件参数e)
{
_phoneCamera.Focus();
}
受保护的覆盖无效OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
//我们正在离开此页面,将不会扫描任何条形码
_scanTimer.Stop();
如果(_phoneCamera!=null)
{
//清理
_phoneCamera.Dispose();
_phoneCamera.Initialized-=cam_Initialized;
CameraButtons.ShutterKeyHalfPressed-=CameraButtons\u ShutterKeyHalfPressed;
}
}
已初始化无效cam_(对象发送器,Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
如果(如成功)
{
this.Dispatcher.BeginInvoke(委托()
{
_phoneCamera.FlashMode=FlashMode.Off;
_previewBuffer=新的WriteableBitmap((int)\u phoneCamera.PreviewResolution.Width,(int)\u phoneCamera.PreviewResolution.Height);
_条形码阅读器=新条形码阅读器();
//默认情况下,条形码阅读器将扫描所有支持的条形码类型
//如果我们想限制应用程序可以读取的条形码类型,
//我们可以通过将每种格式添加到此列表对象来实现
//var supportedBarcodeFormats=新列表();
//supportedBarcodeFormats.Add(BarcodeFormat.QR_代码);
//supportedBarcodeFormats.Add(BarcodeFormat.DATA_矩阵);
//_bcReader.PossibleFormats=受支持的条形码格式;
_barcodeReader.TryHarder=true;
_条形码阅读器.ResultFound+=\u bcReader\u ResultFound;
_scanTimer.Start();
});
}
其他的
{
Dispatcher.BeginInvoke(()=>
{