在C#中生成一个二维码扫描程序,核心工作是调用摄像头获取实时画面,并使用二维码解码库对每一帧图像进行识别。下面以WinForms为例,使用AForge.NET控制摄像头,用ZXing.Net完成解码。

一、准备工作
通过NuGet安装以下两个包:
- AForge.Video.DirectShow:用于枚举和调用摄像头
- ZXing.Net:用于二维码识别
二、调用摄像头并显示画面
使用FilterInfoCollection获取可用摄像头,用VideoSourcePlayer组件播放视频流。
using AForge.Video;
using AForge.Video.DirectShow;
using System.Windows.Forms;
public class CameraForm : Form
{
private FilterInfoCollection cameras;
private VideoCaptureDevice cameraDevice;
private VideoSourcePlayer videoPlayer;
public CameraForm()
{
videoPlayer = new VideoSourcePlayer();
videoPlayer.Dock = DockStyle.Fill;
// 摄像头每取到一帧就触发该事件
videoPlayer.NewFrame += VideoPlayer_NewFrame;
this.Controls.Add(videoPlayer);
// 枚举本机摄像头
cameras = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (cameras.Count > 0)
{
cameraDevice = new VideoCaptureDevice(cameras[0].MonikerString);
videoPlayer.VideoSource = cameraDevice;
cameraDevice.Start();
}
}
private void VideoPlayer_NewFrame(object sender, ref Bitmap image)
{
// image就是当前摄像头帧,识别逻辑在另一方法处理
ScanQRCode(image);
}
}
三、识别二维码内容
在每一帧到达时,用ZXing的BarcodeReader对Bitmap进行解码。注意要在后台线程或加锁处理,避免界面卡顿。
using ZXing;
using System.Drawing;
private string lastResult = string.Empty;
private void ScanQRCode(Bitmap frame)
{
// 配置解码选项,只识别二维码
BarcodeReader reader = new BarcodeReader();
reader.Options.PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE };
reader.AutoRotate = true;
// 解码当前帧
Result result = reader.Decode(frame);
if (result != null && result.Text != lastResult)
{
lastResult = result.Text;
// 识别成功,输出内容
MessageBox.Show("二维码内容:" + lastResult);
}
}
四、释放资源
关闭窗体时要停止摄像头,防止设备被占用:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (cameraDevice != null && cameraDevice.IsRunning)
{
cameraDevice.SignalToStop();
cameraDevice.WaitForStop();
}
base.OnFormClosing(e);
}
五、常见问题
| 问题 | 说明 |
|---|---|
| 找不到摄像头 | 检查FilterInfoCollection数量,确认系统已识别设备 |
| 识别太慢 | 可缩小解码图像尺寸,或降低摄像头分辨率 |
| 误识别 | 在ScanQRCode中增加去重与间隔时间判断 |
按照上面的步骤,你就可以用C#生成一个简单的二维码扫描程序,并调用摄像头实时识别二维码。实际项目中还可把识别结果写到数据库或发起网络请求。