using AForge.Video;
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestApp05
{
    public partial class CamTestForm : Form
    {
        private FilterInfoCollection VideoCaptureDevices;
        private VideoCaptureDevice FinalVideo;
        private VideoCaptureDeviceForm captureDevice = new VideoCaptureDeviceForm();

        public CamTestForm()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            FinalVideo.Start();
        }

        private void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            camBox.Image = (Bitmap) eventArgs.Frame.Clone();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (FinalVideo.IsRunning == true) {
                FinalVideo.Stop();
                pictureBox.Image = null;
                pictureBox.Invalidate();
                camBox.Image = null;
                camBox.Invalidate();
            }
        }

        private void btnSnapshot_Click(object sender, EventArgs e)
        {
            pictureBox.Image = (Bitmap) camBox.Image.Clone();
        }

        private void CamTestForm_Load(object sender, EventArgs e)
        {
            VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo device in VideoCaptureDevices) {
                comboBox.Items.Add(device);
            }
            captureDevice = new VideoCaptureDeviceForm();
            comboBox.SelectedIndex = 0;

            FinalVideo = new VideoCaptureDevice(VideoCaptureDevices[comboBox.SelectedIndex].MonikerString);
            FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
        }

        private void CamTestForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (FinalVideo.IsRunning == true) {
                FinalVideo.Stop();
                Application.Exit();
            }
            else {
                Application.Exit();
            }
        }
    }
}
