DotNET hard-coded fonts

I had problems with numerous cases where users did not have one of the Windows Core fonts installed on their machine (for example, Courier New, Comic Sans MS, Arial). Whenever I try to build one of them, it throws an error, and does not return to a connected or really different font.

What is the best way to create a font if I want it to be a courier, but I'm not particularly attached to it?

+3
source share
3 answers

You can embed fonts as resources and use the keyword unsafe(and must be compiled with "unsafe") to get the fonts ... Here is an example of the code that I used to set the font control user type to "OCR"

private PrivateFontCollection pfc = new PrivateFontCollection ();
private Font _fntOCRFont = null;
private enum FontEnum {
   OCR = 0
};

This is an announcement of a private font collection ... the OCR font is embedded as a resource using a naming convention, where "foo" is the namespace, so the resource name will be "foo.ocraext.ttf" .. Look here at "InitOCRFont", which downloads the font and adds it to the collection:

private void InitOCRFont () {
   try {
      System.IO.Stream streamFont = this.GetType().Assembly.GetManifestResourceStream("foo.ocraext.ttf");
      if (streamFont != null){
          byte[] fontData = new byte[streamFont.Length];
          streamFont.Read(fontData, 0, (int)streamFont.Length);
          streamFont.Close();
          unsafe{
                fixed(byte *pFontData = fontData){
                   this.pfc.AddMemoryFont((System.IntPtr)pFontData, fontData.Length);
                }
          }
      }else{
          throw new Exception("Error! Could not read built-in Font.");
      }
   }catch(Exception eX){
      throw new Exception("InitOCRFont Method - Exception occurred!\nException was: " + eX.Message);
   }
}

, "OCR", , . "InitializeCtlFont", - 10 "-":/p >

private void InitializeCtlFont(){
    this._fntOCRFont = new Font(this.pfc.Families[0], 10.0F, System.Drawing.FontStyle.Bold);
    if (this._fntOCRFont != null){
         foreach(Control ctl in this.Controls){
            if (ctl != null && ((ctl is Label) || (ctl is TextBox))){
                        ctl.Font = this._fntOCRFont;
                    }
         }
    }
}

, , , Dispose:

try{
   if (this._fntOCRFont != null) this._fntOCRFont.Dispose();
}catch{
}
try{
   if (this.pfc != null) this.pfc.Dispose();
}catch{
}

, , , .

+4

, FontFamily.GenericMonospace, Monospace, Courier:

Font f = new Font(FontFamily.GenericMonospace, 12, FontStyle.Regular);

, .

.

+2

. Windows , , . Microsoft Sans Serif XP, Segoe UI . .

Again, if the machine is so confused that it does not have the basic fonts available, it may not have the TrueType font at all. Yes, it will bomb your program. Honestly, this is not something you will have to deal with if it is not a very valuable customer. This is otherwise trivially decided by your customer support team.

+2
source

Source: https://habr.com/ru/post/1735717/


All Articles