I specify the font for the a_Simpler button enter image description here

If this font is not added to the font library:

enter image description here

Then she writes the usual Microsoft Sans Serif

Can I save the a_Simpler font with .exe? or how to solve the problem?

  • WinForms or WPF? - VladD
  • c # WindowsForms - Sauron

1 answer 1

Compilation of responses to en.SO:

The trick is to put the font in the global PrivateFontCollection , and use it from there. (The collection itself, apparently, needs to be put in the main class of the application or other publicly accessible place.)

If you already have it there, and the collection is defined as PrivateFontCollection pfc , use this structure:

 b.Font = new Font(pfc.Families[0], <тут указываете размер>); 

You also need to set UseCompatibleTextRendering to true in the properties of the UI element.

Instead of the index 0, you may need another if you put several fonts in the collection.


How can I add a font to the collection? For this, the AddFontFile and AddMemoryFont methods are used. If you drag a font in a file, then everything is quite simple: pfc.AddFontFile(<тут путь к вашему файлу со шрифтом>); .

If you decide to put the font in the resources, you will need more complex code.

 var fontdata = Properties.Resources.Simpler; // Simpler - имя, которое вы дали шрифту var length = fontdata.Length; // в ресурсах var unsafeData = Marshal.AllocCoTaskMem(length); Marshal.Copy(fontdata, 0, unsafeData, length); pfc.AddMemoryFont(unsafeData, length); Marshal.FreeCoTaskMem(unsafeData); 

Sources: [1] , [2] , [3] , [4] .

  • b.Font = new Font(pfc.Families[0], <тут указываете размер>); Is it possible to take a standard size? not point it out. - Sauron
  • @Sauron: For example, b.Font.Size ? - VladD
  • No, I’m only changing the width and leaving the size as standard. - Sauron
  • @Sauron: And you try it! Before assigning b.Font = ... there is a standard font, which has a standard size. - VladD
  • @Sauron, @VladD, Font class, judging by the examples in MSDN is immutable, so the size, boldness, type and other font parameters have to be set when creating and installing a new font instead of changing the existing one. Apparently the idea is like with lines, once there are many links for one copy - it is forbidden to change, re-create. - rdorn