kyriacoss

Installing a font through C#

Mar 29th, 2015
5,738
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         [DllImport("gdi32", EntryPoint = "AddFontResource")]
  2.         public static extern int AddFontResourceA(string lpFileName);
  3.         [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  4.         private static extern int AddFontResource(string lpszFilename);
  5.         [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  6.         private static extern int CreateScalableFontResource(uint fdwHidden, string
  7.         lpszFontRes, string lpszFontFile, string lpszCurrentPath);
  8.  
  9.         /// <summary>
  10.         /// Installs font on the user's system and adds it to the registry so it's available on the next session
  11.         /// Your font must be included in your project with its build path set to 'Content' and its Copy property
  12.         /// set to 'Copy Always'
  13.         /// </summary>
  14.         /// <param name="contentFontName">Your font to be passed as a resource (i.e. "myfont.tff")</param>
  15.         private static void RegisterFont(string contentFontName)
  16.         {
  17.             // Creates the full path where your font will be installed
  18.             var fontDestination = Path.Combine(System.Environment.GetFolderPath
  19.                                           (System.Environment.SpecialFolder.Fonts), contentFontName);
  20.  
  21.             if (!File.Exists(fontDestination))
  22.             {
  23.                 // Copies font to destination
  24.                 System.IO.File.Copy(Path.Combine(System.IO.Directory.GetCurrentDirectory(), contentFontName), fontDestination);
  25.  
  26.                 // Retrieves font name
  27.                 // Makes sure you reference System.Drawing
  28.                 PrivateFontCollection fontCol = new PrivateFontCollection();
  29.                 fontCol.AddFontFile(fontDestination);
  30.                 var actualFontName = fontCol.Families[0].Name;
  31.  
  32.                 //Add font
  33.                 AddFontResource(fontDestination);
  34.                 //Add registry entry  
  35.                 Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",
  36.         actualFontName, contentFontName, RegistryValueKind.String);
  37.             }
  38.         }
RAW Paste Data