Using custom fonts in C# application
Recently I wanted to embed custom fonts in my application. After some googling and mixing the solution is this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
[DllImport("gdi32.dll")] private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts); public static PrivateFontCollection private_fonts = new PrivateFontCollection(); public static void LoadFont() { // Use this if you can not find your resource System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); string resource = "Test.Images.MyFont.ttf"; // receive resource stream Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); //create an unsafe memory block for the data System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length); //create a buffer to read in to Byte[] fontData = new Byte[fontStream.Length]; //fetch the font program from the resource fontStream.Read(fontData, 0, (int)fontStream.Length); //copy the bytes to the unsafe memory block Marshal.Copy(fontData, 0, data, (int)fontStream.Length); // We HAVE to do this to register the font to the system (Weird .NET bug !) uint cFonts = 0; AddFontMemResourceEx(data, (uint)fontData.Length, IntPtr.Zero, ref cFonts); //pass the font to the font collection private_fonts.AddMemoryFont(data, (int)fontStream.Length); //close the resource stream fontStream.Close(); //free the unsafe memory Marshal.FreeCoTaskMem(data); } ... // Apply font to TextEdit LoadFont(); tbPassword.PasswordChar = 'A'; tbPassword.Font = new Font(private_fonts.Families[0], 8); ... |
Add your font file to project resources : Embed Font Use the code above and you are ready to go. This solution also works with DevExpress edit components Nice tool to quickly make your font… Read More »