Search code examples
c#webcamaforgewebcam-capture

How to take photo from webcam every one minute?


I'm trying to take a snapshot through my webcam. This is my code:

using System;
using System.Text;
using System.Drawing;
using System.Threading;

using AForge.Video.DirectShow;
using AForge.Video;

namespace WebCamShot
{
    class Program
    {
        static FilterInfoCollection WebcamColl;
        static VideoCaptureDevice Device;

        static void Main(string[] args)
        {
            WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Console.WriteLine("Press Any Key To Capture Photo !");
            Console.ReadKey();
            Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
            Device.NewFrame += Device_NewFrame;
            Device.Start();
            Console.ReadLine();
        }

        static void Device_NewFrame(object sender, NewFrameEventArgs e)
        {
            Bitmap Bmp = (Bitmap)e.Frame.Clone();
            Bmp.Save("D:\\Foo\\Bar.png");
            Console.WriteLine("Snapshot Saved.");
            /*
            Console.WriteLine("Stopping ...");
            Device.SignalToStop();
            Console.WriteLine("Stopped .");
            */
        }
    }
}

It works well, but now I want to use my code for taking a snapshot every one minute.

Due to this reason, I added this line of code: Thread.Sleep(1000 * 60); // 1000 Milliseconds (1 Second) * 60 == One minute.

Unfortunately, This line doesn't giving me the wanted result - It still taking the snapshots like earlier, but it just saving the photos in the file every minute. What I actually want to do, is that my code will trigger the "Device_NewFrame" event every one minute.

How can I do it? I will glad to get some help.. Thhank You !

EDIT: As Armen Aghajanyan offered, I added timer to my code. This timer Initializes the device object every one minute, registers the new Device object to the Device_NewFrame event and starts the activity of the Device. After that, I'm uncommented this code in the event's body:

Console.WriteLine("Stopping ...");
Device.SignalToStop();
Console.WriteLine("Stopped .");

Now the code is taking a snapshot every one minute.


Solution

  • I would recommend using Timer.Elapsed event. The implementation is straight forward and clean. http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx