using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
namespace FCOMMON
{
    public partial class fWebCamera : Form
    {
        VideoCapture _capture;
        public Bitmap bmp = null;

        public fWebCamera(int idx = 0)
        {
            InitializeComponent();
            this._capture = new VideoCapture(idx);
            //capture.SetCaptureProperty(CapProp.FrameWidth, 648);
            //_capture.SetCaptureProperty(CapProp.FrameHeight, 480);
            this._capture.ImageGrabbed += capture_ImageGrabbed;
            this.FormClosing += fWebCamera_FormClosing;
        }

        void fWebCamera_FormClosing(object sender, FormClosingEventArgs e)
        {
            this._capture.ImageGrabbed -= capture_ImageGrabbed;
            if (this._capture.IsOpened) this._capture.Stop();
            this._capture.Dispose();
        }

        private void fWebCamera_Load(object sender, EventArgs e)
        {
            srcimage = new Mat();
            this._capture.Start();
            this.imageBox1.Image = srcimage;
        }

         Mat srcimage;
         DateTime lastimage = DateTime.Now;

        void capture_ImageGrabbed(object sender, EventArgs e)
        {
            if (this._capture.Retrieve(srcimage, 0))
            {
                lastimage = DateTime.Now;
                if (srcimage != null && srcimage.Width > 10 && srcimage.Height > 10)
                {
                    if (this.Disposing || this.IsDisposed) return;
                    try
                    {
                        this.imageBox1.Image = srcimage;
                        this.imageBox1.Invalidate();
                    } catch 
                    {

                    }
                    //var img = this.pictureBox1.Image;
                 
                    //if (img != null) img.Dispose();
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _capture.Stop();
            while(true)
            {
                var ts = DateTime.Now - lastimage;
                if (ts.TotalSeconds >= 1.0)
                    break;
                Application.DoEvents();
            }
            bmp = srcimage.Bitmap;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
