我正在尝试通过我的网络摄像头拍摄快照。这是我的代码:
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 .");
*/
}
}
}
它运行良好,但现在我想使用我的代码每分钟拍摄一次快照。
由于这个原因,我添加了这行代码:Thread.Sleep(1000 * 60); // 1000 Milliseconds (1 Second) * 60 == One minute.
不幸的是,这条线并没有给我想要的结果 - 它仍然像以前一样拍摄快照,但它只是每分钟将照片保存在文件中。我真正想做的是,我的代码将每分钟触发一次“Device_NewFrame”事件。
我该怎么做?我很乐意得到一些帮助。谢谢!
编辑:正如 Armen Aghajanyan 提供的,我在代码中添加了计时器。该定时器每隔一分钟初始化一次设备对象,将新的设备对象注册到Device_NewFrame事件并启动设备的活动。之后,我在事件正文中取消注释此代码:
Console.WriteLine("Stopping ...");
Device.SignalToStop();
Console.WriteLine("Stopped .");
现在代码每分钟拍摄一次快照。