UPDATE:
I have changed the code and removed anything that could be writing simultaneously with pictureBox1
and I still get the same error but at a different place. I will attach a picture of the error. I have updated the code.
Okay so I have tried looking everywhere for answers to this error but I got nowhere. I found answers such as g.Dispose();
and "acquiring lock on an image". However, my project is kind of different because it is not a still image.
It crashes after around 504 frames. I will attach a picture of where I get the error and I will link the code as well for the webcam display.
I have no idea how is pictureBox1
is being used somewhere else when all I am doing in the Start button is just starting the webcam and saving frames to a folder.
I am using AForge library for webcam access. And when I simply press the Start webcam button and wait a couple of minutes I get this error:
System.InvalidOperationException was unhandled HResult=-2146233079
Message=Object is currently in use elsewhere. Source=System.Drawing StackTrace: at System.Drawing.Graphics.CheckErrorStatus(Int32 status) at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height) at System.Drawing.Graphics.DrawImage(Image image, Rectangle rect) at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe) at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException:
Picture of error message: https://i.stack.imgur.com/s4Vts.jpg
Code:
//Initializing Webcam
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
//Start Webcam
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
cam.Start();
}
//Displaying Video from webcam in Picture box
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap image = (Bitmap)eventArgs.Frame.Clone();
Bitmap image1 = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = image;
//Drawing lines across the pictureBox
g1 = Graphics.FromImage(image);
Pen gridPen = new Pen(Color.Black, 5);
g1.DrawLine(gridPen, 0, 5, 805, 5);
g1.DrawLine(gridPen, 0, 100, 805, 100);
g1.DrawLine(gridPen, 0, 195, 805, 195);
g1.DrawLine(gridPen, 0, 290, 805, 290);
g1.DrawLine(gridPen, 0, 385, 805, 385);
g1.DrawLine(gridPen, 0, 480, 805, 480);
}