Resolved Embedded Font code causing runtime error

servantofone

Member
Joined
Apr 20, 2010
Messages
13
Programming Experience
5-10
I grabbed some code to embed a font from the following discussion (Google cache of discussion):

Expert Exchange Embedded Font discussion

It works to embed the font; however, I now experience random crashes at runtime (in XP). If I comment out the calls to GetFont, then the crashes cease. If I uncomment the GetFont calls, it crashes randomly again.

Any insight you might provide would be great. I'm running Visual Studio 2008 Professional on XP Service Pack 3.

EmbeddedFont.vb
VB.NET:
Imports System.Drawing.Text
Imports System.IO
Imports System.Reflection

Public Class EmbeddedFont
    Private Declare Auto Function AddFontMemResourceEx Lib "Gdi32.dll" _
        (ByVal pbFont As IntPtr, ByVal cbFont As Integer, _
        ByVal pdv As Integer, ByRef pcFonts As Integer) As IntPtr


    Public Shared Function GetFont(ByVal fontName As String) As FontFamily

        Dim exeCurrent As [Assembly] = [Assembly].GetExecutingAssembly()
        Dim nameSpc As String = exeCurrent.GetName().Name.ToString()
        Dim fontCollection As New PrivateFontCollection
        Dim loadStream As Stream = exeCurrent.GetManifestResourceStream( _
            nameSpc + "." + fontName)
        Dim byteBuffer(CType(loadStream.Length, Integer)) As Byte

        loadStream.Read(byteBuffer, 0, Int(CType(loadStream.Length, Integer)))

        Dim fontPtr As IntPtr = _
            Runtime.InteropServices.Marshal.AllocHGlobal( _
            Runtime.InteropServices.Marshal.SizeOf(GetType(Byte)) * _
                byteBuffer.Length)

        Runtime.InteropServices.Marshal.Copy(byteBuffer, 0, fontPtr, byteBuffer.Length)

        fontCollection.AddMemoryFont(fontPtr, byteBuffer.Length)

        Dim pcFonts As Int32 = 1

        AddFontMemResourceEx(fontPtr, byteBuffer.Length, 0, pcFonts)
        Runtime.InteropServices.Marshal.FreeHGlobal(fontPtr)
        Return fontCollection.Families(0)

    End Function

End Class

Runtime error:
System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Source="System.Drawing"
StackTrace:
at System.Drawing.SafeNativeMethods.Gdip.GdipGetFamilyName(HandleRef family, StringBuilder name, Int32 language)
at System.Drawing.FontFamily.GetName(Int32 language)
at System.Drawing.FontFamily.get_Name()
at System.Windows.Forms.Internal.WindowsFont.FromFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.Internal.WindowsGraphicsCacheManager.GetWindowsFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.TextRenderer.DrawText(IDeviceContext dc, String text, Font font, Rectangle bounds, Color foreColor, TextFormatFlags flags)
at System.Windows.Forms.Label.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Label.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)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Form.DefWndProc(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmSysCommand(Message& m)
at System.Windows.Forms.Form.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)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Form.DefWndProc(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmNcButtonDown(Message& m)
at System.Windows.Forms.Form.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)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at PromiseCard.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
 
Last edited:
I figured it out. I changed my code from:

VB.NET:
lblLight1.Font = New Font(EmbeddedFont.GetFont("Light.ttf"), 39, FontStyle.Regular)
lblLight2.Font = New Font(EmbeddedFont.GetFont("Light.ttf"), 39, FontStyle.Regular)

to

VB.NET:
Dim fontLight39 As New Font(EmbeddedFont.GetFont("Light.ttf"), 39, FontStyle.Regular)
lblLight1.Font = fontLight39
lblLight2.Font = fontLight39

That took care of the random crashing.
 
Back
Top