Font importation

- Posted in Uncategorized by

How to import a font into a C# program:

      //interop to allow import of game font
  [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
      IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

Also before the form's constructor, add a form-level variable (but make sure it comes after the Win32 function import):

Font myFont;

If you have the desired font as a .resx resource in your Visual Studio project, you'll use the following code inside the form's constructor:

//Form1 constructor code that pulls game font into memory
      byte[] fontData = Properties.Resources.brushstr;
      IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
      System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
      uint dummy = 0;
      fonts.AddMemoryFont(fontPtr, Properties.Resources.brushstr.Length);
      AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.brushstr.Length, IntPtr.Zero, ref dummy);
      System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);

      myFont = new Font(fonts.Families[0], 16.0F);

Import a font using c-sharp

- Posted in Coding by
using System.Runtime.InteropServices;

      //interop to allow import of game font
      [System.Runtime.InteropServices.DllImport("gdi32.dll")]
      private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
          IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

Also before the form's constructor, add a form-level variable (but make sure it comes after the Win32 function import):

Font myFont;

If you have the desired font as a .resx resource in your Visual Studio project, you'll use the following code inside the form's constructor:

//Form1 constructor code that pulls game font into memory
          byte[] fontData = Properties.Resources.brushstr;
          IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
          System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
          uint dummy = 0;
          fonts.AddMemoryFont(fontPtr, Properties.Resources.brushstr.Length);
          AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.brushstr.Length, IntPtr.Zero, ref dummy);
          System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);

          myFont = new Font(fonts.Families[0], 16.0F);