How do I embed my own fonts in a WinForms app?

后端 未结 5 1337
醉酒成梦
醉酒成梦 2020-12-02 15:23

I want to embed fonts in my WinForms application so that I don\'t have to worry about them being installed on the machine. I\'ve searched a bit on the MSDN site and found a

5条回答
  •  既然无缘
    2020-12-02 16:17

    // specify embedded resource name
    string resource = "embedded_font.PAGAP___.TTF";
    
    // receive resource stream
    Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
    
    // create an unsafe memory block for the font data
    System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
    
    // create a buffer to read in to
    byte[] fontdata = new byte[fontStream.Length];
    
    // read the font data 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);
    
    // pass the font to the font collection
    private_fonts.AddMemoryFont(data, (int)fontStream.Length);
    
    // close the resource stream
    fontStream.Close();
    
    // free up the unsafe memory
    Marshal.FreeCoTaskMem(data);
    

提交回复
热议问题