Question Strange error

Pirahnaplant

Well-known member
Joined
Mar 29, 2009
Messages
75
Programming Experience
3-5
I always get this error during the Paint event:
System.AccessViolationException was unhandled
The weird thing is that it doesn't happen the first time it goes through.
Here's the code.

VB.NET:
    Friend CustomFont As Font = GetCustomFont()

    Private Function GetCustomFont() As Drawing.Font
        Try
            Dim PFC As Drawing.Text.PrivateFontCollection
            Dim NewFont_FF As Drawing.FontFamily
            'Create a new font collection
            PFC = New Drawing.Text.PrivateFontCollection
            'Add the font file to the new font
            PFC.AddFontFile(My.Application.Info.DirectoryPath & "\CustomFont.ttf")
            'Retrieve your new font
            NewFont_FF = PFC.Families(0)
            Return New Drawing.Font(NewFont_FF, 12, FontStyle.Regular, GraphicsUnit.Point)
        Catch
            Return New Drawing.Font("Courier New", 12, FontStyle.Regular, GraphicsUnit.Point)
        End Try
    End Function

    Private Sub SymbolImg_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles SymbolImg.Paint
        For loops1 As Integer = 0 To 10
            For loops2 As Integer = 0 To 19
                e.Graphics.DrawString(Symbols(loops1, loops2), CustomFont, Brushes.Black, 20 * loops2, 20 * loops1)
            Next
        Next
    End Sub

Symbols is just a 2 dimensional array of characters.

Edit: I'm pretty sure it has something to do with the custom font.
 
Last edited:
Google says that error usually occurs when you try to read protected memory.

What is Symbols?
 
Are you using a BackgroundWorker or somehow multithreading?

I think I've seen this AccessViolationException sometimes happen when you update the UI through a a thread other than the one thread that created the UI in the first place.
 
Symbols is a 2-dimensional array of characters like this:

Dim Symbols As Char(,) = {{"a", "b"...

Maybe that's the problem? Maybe you coudl add a temporary String variable which gets the value before the function and then passes it to DrawString-Method.

VB.NET:
    Private Sub SymbolImg_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles SymbolImg.Paint
        Dim temp As String = String.Empty

        For loops1 As Integer = 0 To 10
            For loops2 As Integer = 0 To 19
                temp = Symbols(loops1, loops2)
                e.Graphics.DrawString(temp, CustomFont, Brushes.Black, 20 * loops2, 20 * loops1)
            Next
        Next
    End Sub

Bobby
 
Back
Top