下面是一个简单的示例代码,可以读取视频采集卡并实时显示到 WinForm 中:

using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;

namespace VideoCapture
{
    public partial class MainForm : Form
    {
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoDevice;
        private VideoCapabilities[] videoCapabilities;

        public MainForm()
        {
            InitializeComponent();

            // 获取可用的视频采集设备
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count == 0)
            {
                MessageBox.Show('没有可用的视频采集设备!');
                return;
            }

            // 将可用的视频采集设备添加到下拉列表中
            foreach (FilterInfo device in videoDevices)
            {
                comboBoxDevices.Items.Add(device.Name);
            }
            comboBoxDevices.SelectedIndex = 0;
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            // 初始化视频采集设备
            if (videoDevice != null && videoDevice.IsRunning)
            {
                videoDevice.SignalToStop();
                videoDevice.WaitForStop();
            }
            videoDevice = new VideoCaptureDevice(videoDevices[comboBoxDevices.SelectedIndex].MonikerString);
            videoDevice.NewFrame += new NewFrameEventHandler(videoDevice_NewFrame);

            // 获取视频采集设备支持的视频分辨率
            videoCapabilities = videoDevice.VideoCapabilities;
            comboBoxResolution.Items.Clear();
            foreach (VideoCapabilities capabilty in videoCapabilities)
            {
                comboBoxResolution.Items.Add(capabilty.FrameSize.Width + 'x' + capabilty.FrameSize.Height);
            }
            if (comboBoxResolution.Items.Count > 0)
            {
                comboBoxResolution.SelectedIndex = 0;
            }

            // 启动视频采集设备
            videoDevice.Start();
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            // 停止视频采集设备
            if (videoDevice != null && videoDevice.IsRunning)
            {
                videoDevice.SignalToStop();
                videoDevice.WaitForStop();
            }
        }

        private void videoDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // 显示视频画面
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
            pictureBoxVideo.Image = bitmap;
        }
    }
}

在窗体设计器中添加一个 PictureBox 控件和两个 Button 控件,分别命名为 pictureBoxVideo、buttonStart 和 buttonStop。然后在按钮的 Click 事件中调用上述代码即可。需要引用 AForge.Video 和 AForge.Video.DirectShow 两个命名空间。

C# 实时视频采集卡显示 WinForm - AForge.NET 教程

原文地址: https://www.cveoy.top/t/topic/oaE5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录