I have solved it. In Constructor I have initialized an event, but in Form1 I was overwriting videoSource, so the event wasn't initialized.
The Right code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AForge.Video.DirectShow;
using System.Drawing;
using AForge.Video;
namespace CameraDevice
{
public class CameraImaging
{
public FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice );
private VideoCaptureDevice _videoSource;
public Bitmap bitmap = new Bitmap(10, 10);
public VideoCaptureDevice videoSource
{
get
{
return _videoSource;
}
set
{
_videoSource = value;
_videoSource.NewFrame +=new NewFrameEventHandler(videoSource_NewFrame);
}
}
public CameraImaging(VideoCaptureDevice videoDevice)
{
VideoCaptureDevice videoSource = videoDevice;
}
public CameraImaging()
{
}
private void videoSource_NewFrame( object sender, NewFrameEventArgs eventArgs )
{
lock (bitmap)
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
}
}
}
}
Form1:
...
private void VideoRecording()
{
camImg.videoSource.Start();
while (!StopVideo)
{
lock (mImageLock)
{
Bitmap tmp = (Bitmap)camImg.bitmap.Clone();
if (InvokeRequired)
{
BeginInvoke(new MethodInvoker(() =>
{
pictureBox1.Image = tmp;
pictureBox1.Invalidate();
}));
}
else
{
pictureBox1.Image = tmp;
pictureBox1.Invalidate();
}
}
Thread.Sleep(33);
}
camImg.videoSource.Stop();
}
private void btnStartVideo_Click(object sender, EventArgs e)
{
StopVideo = false;
try
{
camImg.videoSource = new VideoCaptureDevice (camImg.videoDevices[cbCameraDevices.SelectedIndex].MonikerString);
thrVideo = new Thread(VideoRecording);
lblRecording.Visible = true;
thrVideo.Start();
Thread.Sleep(1000);
}
catch (Exception)
{
MessageBox.Show("No camera was chosen!", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
...