TKGhoul TKGhoul - 3 months ago 31
Vb.net Question

AccessViolationException was unhandled [VB.Net] [Emgucv]


Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.


This was the error after I set the Image to my PictureBox. Its working fine but later on the error just pop-out.

Here is my code.

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
Dim cap As New Capture() 'first line

PictureBox1.Image = cap.QueryFrame.ToBitmap 'this line AccessViolationException
Catch ex As Exception
Timer1.Stop()
MsgBox("CAMERA ERROR " & ex.Message)
End Try
End Sub

Private Sub MetroTile1_Click(sender As Object, e As EventArgs) Handles MetroTile1.Click
Try
Dim cap As New Capture() 'first line
Select Case MetroTile1.Text
Case "Capture"
Timer1.Start()
MetroTile1.Text = "OK"
Case "OK"
Timer1.Stop()
frmStudentAddEdit.picImage.Image = PictureBox1.Image
MetroTile1.Text = "Capture"
Me.Close()
End Select
Catch ex As Exception
Timer1.Stop()
End Try
End Sub


The
cap.QueryFrame.ToBitmap
is the AccessViolationException was unhandled error.

How can I Fix this ? What causing this error ? Please Help.

Answer

Aim for something like the following.

  1. Capture is a member of the form (not created new each time)
  2. oldImage is disposed of after replacing

Private mCapture As Capture

Private Sub Form12_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    mCapture = New Capture()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Try
        Dim oldImage = PictureBox1.Image
        Dim newFrame = mCapture.QueryFrame.ToBitmap
        PictureBox1.Image = newFrame.ToBitmap
        If oldImage IsNot Nothing Then oldImage.Dispose()
    Catch ex As Exception
        Timer1.Stop()
        MsgBox("CAMERA ERROR " & ex.Message)
    End Try
End Sub

Private Sub MetroTile1_Click(sender As Object, e As EventArgs) Handles MetroTile1.Click
    Try
        Select Case MetroTile1.Text
            Case "Capture"
                Timer1.Start()
                MetroTile1.Text = "OK"
            Case "OK"
                Timer1.Stop()
                frmStudentAddEdit.picImage.Image = PictureBox1.Image
                MetroTile1.Text = "Capture"
                Me.Close()
        End Select
    Catch ex As Exception
        Timer1.Stop()
    End Try
End Sub
Comments