title: Get Webcam stream using Aforge.NET in C# and WPF
body: <p>I want to capture a webcam feed using my camera. For that I am using the 2 references: <code>AForge.Video.dll</code> and <code>AForge.Video.DirectShow.dll</code>.</p>
  
  <p><a href="http://irslab.blogspot.com/2010/07/webcam-using-aforgenet-part-ii.html" rel="nofollow noreferrer">Here's</a> a snippet I found: </p>
  
  <pre class="lang-cs prettyprint-override"><code>public FilterInfoCollection CamsCollection;
  public VideoCaptureDevice Cam = null;
  
  void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
  {   
    frameholder.Source = (Bitmap)eventArgs.Frame.Clone(); 
    /* ^
     * Here it cannot convert implicitly from System.Drawing.Bitmap to
     * System.Windows.Media.ImageSource
     */
  
  }
  
  private void startcam_Click(object sender, RoutedEventArgs e)
  {
    CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
  
    Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString);
    Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
    Cam.Start();
  }
  
  private void stopcam_Click(object sender, RoutedEventArgs e)
  {
    Cam.Stop();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>They use a <code>PictureBox</code> to display the frames. As I am working in WPF, I used <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/833ca60f-6a11-4836-bb2b-ef779dfe3ff0/" rel="nofollow noreferrer">this</a></p>
  
  <p>To sum up here's what my code looks like currently.</p>
  
  <pre><code>public FilterInfoCollection CamsCollection;
  public VideoCaptureDevice Cam = null;
  
  
  void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
  {
  
      System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
  
  
      BitmapImage bi = new BitmapImage();
      bi.BeginInit ();
  
      MemoryStream ms = new MemoryStream ();
  
      imgforms.Save(ms, ImageFormat.Bmp);
  
      ms.Seek(0, SeekOrigin.Begin);
      bi.StreamSource  = ms;
      frameholder.Source = bi; 
     /* ^ runtime error here because `bi` is occupied by another thread.
      */
      bi.EndInit();
  }
  
  private void startcam_Click(object sender, RoutedEventArgs e)
  {
  
      CamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
  
      Cam = new VideoCaptureDevice(CamsCollection[1].MonikerString);
      Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
      Cam.Start();
  }
  
  private void stopcam_Click(object sender, RoutedEventArgs e)
  {
      Cam.Stop();
  }
  </code></pre>