Skip to main content
 首页 » 编程设计

c#之如何每隔一分钟从网络摄像头拍照

2024年02月13日9unruledboy

我正在尝试通过我的网络摄像头拍摄快照。 这是我的代码:

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 毫秒(1 秒)* 60 == 一分钟。

不幸的是,这一行没有给我想要的结果——它仍然像之前一样拍摄快照,但它只是每分钟将照片保存在文件中。我真正想要做的是,我的代码将每隔一分钟触发一次“Device_NewFrame”事件。

我该怎么做?我很乐意得到一些帮助。谢谢!

编辑:正如 Armen Aghajanyan 提供的那样,我在我的代码中添加了计时器。 该计时器每隔一分钟初始化一次设备对象,将新的设备对象注册到 Device_NewFrame 事件中并启动设备的事件。 之后,我取消注释事件正文中的这段代码:

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

现在代码每隔一分钟拍摄一次快照。

请您参考如下方法:

我建议使用 Timer.Elapsed 事件。实现简单明了。 http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx