I'm creating wpf application and capturing images with my usb webcam. The library I'm using is Aforge. Everything is fine, I mean I get the live stream from the webcam and I'm able to capture images etc. But the problem is when I close the program camera is still running (Yellow LED is showing) and the program is not ending. How could I get the camera stopped?
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (WebCam != null)
if (WebCam.IsRunning)
{
WebCam.SignalToStop();
WebCam.WaitForStop();
WebCam = null;
}
}
this is how I'm using NewFreameEventArgs
to get stream
public void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
System.Drawing.Image img = (Bitmap)eventArgs.Frame.Clone();
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
previewWindow.Source = bi;
mainCameraImageControl.Source = bi;
}));
}
catch (Exception ex)
{
}
}
I suggest you should check if you have registered for any event of webcam. If yes, unsubscribe the same.
WebCam.NewFrame -= new NewFrameEventHandler(WebCam_NewFrameReceived);
Edit: Reply to your comments and edited question
WebCam.NewFrame -= new NewFrameEventHandler(WebCam_NewFrameReceived);
Dispatcher.CurrentDispatcher.InvokeShutdown();
WebCam.SignalToStop();
WebCam.WaitForStop();
First, unsubscribe the events. Then call InvokeShutdown()
. Following is from Microsoft link:
The Dispatcher does not shut down completely until the event queue unwinds.
This way, events and dispatchers are disconnected from instance. Then you signal the cam to stop and wait for stop.