Hack Forums
[.NET] Using custom font from file. - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] Using custom font from file. (/showthread.php?tid=5335869)



Using custom font from file. - Trinsechacker - Jul 12, 2016

After hours of research tonight (its 5am and im pissed and haven't gotten far) I have still not managed to find a method that works for me. I have loaded it from the resources and even attempted to load if from the startup location of my executable. Every time I get close (or feel I am close) to loading it, I receive the error "File not found", though clearly the file is there and the code points directly to the .ttf file. Can someone give me an idea of how I would override the default font in a form with this .ttf file? 😶

PS. I have given the executable "Administrative Privileges", and still to no avail. Thoughts? Ideas? Thank you in advance to any help you may give me.


* - Zilog80 - Jul 12, 2016

"File not found" is a very descriptive message.

Make sure your ttf file in in your Debug/Release folder and also check in the source how you are loading the file.


* - t1me - Jul 14, 2016

I've struggled with the same thing, I found this, though.
htt p://zerosandtheone.com/blogs/vb/archive/2009/11/20/vb-net-include-a-font-as-an-embedded-resource-in-your-application.aspx


* - Josh‎ - Jul 15, 2016

So this is converted to Vb.NET from the MaterialSkin theme:

Code
Public Class FontHelper

    <Runtime.InteropServices.DllImport("gdi32.dll")>
    Private Shared Function AddFontMemResourceEx(pbFont As IntPtr, cbFont As UInteger, pvd As IntPtr, <Runtime.InteropServices.[In]> ByRef pcFonts As UInteger) As IntPtr
    End Function

    Private Shared ReadOnly privateFonts As New Drawing.Text.PrivateFontCollection()

    Public Shared Function LoadFont(ByVal resource() As Byte) As Drawing.FontFamily
        Dim length As Integer = resource.Length
        Dim fontPtr As IntPtr = Runtime.InteropServices.Marshal.AllocCoTaskMem(length)
        Runtime.InteropServices.Marshal.Copy(resource, 0, fontPtr, length)

        Dim cFonts As UInteger = 0
        AddFontMemResourceEx(fontPtr, UInteger.Parse(length), IntPtr.Zero, cFonts)
        privateFonts.AddMemoryFont(fontPtr, length)

        Return privateFonts.Families.Last
    End Function
End Class

It gets a font file from resources, and converts it to a font family. You would use it as follows:
Code
Dim f As New Font(FontHelder.LoadFont(My.Resources.TtfFile), 12)