Click here to Skip to main content
15,892,537 members
Articles / Multimedia / GDI+

Webcamera, Multithreading and VFW

Rate me:
Please Sign up or sign in to vote.
4.79/5 (22 votes)
15 Feb 2008CPOL5 min read 234.1K   9.5K   137  
An article on webcamera frame-grabbing in a multi-thread environment
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using SevenZ.WebCamera;
using SevenZ.ImageProcessing;

namespace SevenZ.WebCam
{
   public partial class FormMain : Form
   {
      int time = 0;
      bool bRunning = false;

      WebCameraDevice camDevice;

      public FormMain()
      {
         InitializeComponent();
         WebCameraDeviceManager camManager = new WebCameraDeviceManager();
         cmbDevices.Items.AddRange(camManager.Devices);
         cmbDevices.SelectedIndex = 0;
      }


      void camDevice_OnCameraFrame(object sender, WebCameraEventArgs e)
      {
         // img processing: 20-30 ms
         ImageProcessing.Filters.Flip(e.Frame, false, true);
         camDevice.Set();

         pictureBox.Image = chkGrayScale.Checked ?
            ImageProcessing.Filters.ToGrayScale(e.Frame) :
            e.Frame;

         this.Text = "FPS: " + (1000 / (Environment.TickCount - time)).ToString();
         time = Environment.TickCount;
         
      }

      private void btnStart_Click(object sender, EventArgs e)
      {
         if (bRunning = !bRunning)
         {
            camDevice = new WebCameraDevice(320, 200, 25, cmbDevices.SelectedIndex, this.Handle.ToInt32());
            camDevice.OnCameraFrame += new WebCameraFrameDelegate(camDevice_OnCameraFrame);
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            camDevice.Start();
            btnDeviceProperties.Enabled = true;
            btnStart.Text = "Stop";
         }
         else
         {
            camDevice.Stop();
            btnDeviceProperties.Enabled = false;
            btnStart.Text = "Start";
         }


      }

      private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
      {
         if(camDevice != null)
            camDevice.Stop();
      }

      private void btnDevice_Click(object sender, EventArgs e)
      {
         camDevice.ShowVideoDialog();
      }
   }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Finland Finland
I'm a Master degree student, studying at the University of Joensuu, Finland.

Comments and Discussions