使用C#中的USB网络摄像头自动检测和读取QR码

时间:2018-12-27 17:32:56

标签: c# .net

我用USB网络摄像头创建了QR码阅读器。

按“捕获”按钮,我可以读取QR码。检测到QR码时,我需要自动执行此操作。

我需要这样创建我的应用程序。 Android Studio Tutorial - Scan QR Code by Camera

这是我的代码

using System;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using WebCam_Capture;
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private WebCamCapture _myWebcam;

        private WebCamCapture MyWebcam
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get
            {
                return _myWebcam;
            }

            [MethodImpl(MethodImplOptions.Synchronized)]
            set
            {
                if (_myWebcam != null)
                {
                    _myWebcam.ImageCaptured -= MyWebcam_ImageCaptured;
                }

                _myWebcam = value;
                if (_myWebcam != null)
                {
                    _myWebcam.ImageCaptured += MyWebcam_ImageCaptured;
                }
            }
        }

        private QRCodeDecoder _reader;

        private void MyWebcam_ImageCaptured(object source, WebcamEventArgs e)
        {
            PictureBox1.Image = e.WebCamImage;
        }

        private void StartWebcam()
        {
            try
            {
                StopWebcam();
                MyWebcam = new WebCamCapture();
                MyWebcam.Start(0);
            }
            catch (Exception ex)
            {
            }
        }

        private void StopWebcam()
        {
            try
            {
                MyWebcam.Stop();
                MyWebcam.Dispose();
            }
            catch (Exception ex)
            {
            }
        }

        private void Capture()
        {
            try
            {
                _reader = new QRCodeDecoder();
                TextBox1.Text = _reader.Decode(new QRCodeBitmapImage(PictureBox1.Image as Bitmap));
                MessageBox.Show(@"QR code is detected!");

            }
            catch (Exception ex)
            {
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StartWebcam();
            TextBox1.Clear();
        }

        private void btn_capture_Click(object sender, EventArgs e)
        {
            Capture();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Unity,它们为初学者提供了免费版本并支持C#。 对于QR码/网络摄像头部分,您可以在其资产商店或make a searchGithub