c# - 在VB.net/C#中直接使用资源字体

标签 c# vb.net winforms fonts resources

如何在VB.net/C#中独立应用程序[桌面应用程序]直接使用资源字体而不将字体保存在本地文件系统中?

最佳答案

这是可能的,您需要使用 PrivateFontCollection.AddMemoryFont() 方法。例如,我添加了一个名为“test.ttf”的字体文件作为资源,并像这样使用它:

using System.Drawing.Text;
using System.Runtime.InteropServices;
...
public partial class Form1 : Form {
    private static PrivateFontCollection myFonts;
    private static IntPtr fontBuffer;

    public Form1() {
        InitializeComponent();
        if (myFonts == null) {
            myFonts = new PrivateFontCollection();
            byte[] font = Properties.Resources.test;
            fontBuffer = Marshal.AllocCoTaskMem(font.Length);
            Marshal.Copy(font, 0, fontBuffer, font.Length);
            myFonts.AddMemoryFont(fontBuffer, font.Length);
        }
    }

    protected override void OnPaint(PaintEventArgs e) {
        FontFamily fam = myFonts.Families[0];
        using (Font fnt = new Font(fam, 16)) {
            TextRenderer.DrawText(e.Graphics, "Private font", fnt, Point.Empty, Color.Black);
            //e.Graphics.DrawString("Private font", fnt, Brushes.Black, 0, 0);
        }
    }
}

请注意,fontBuffer 变量是static 的。使用 AddMemoryFont() 时内存管理很困难,只要字体可以使用且 PrivateFontCollection 尚未释放,内存就需要保持有效。如果您没有这种保证,请务必不要调用 Marshal.FreeCoTaskMem(),这是一个非常的常见错误,导致很难诊断文本损坏。只有运气好时,您才会得到 AccessViolationException。使其在程序的整个生命周期内保持有效是简单的解决方案。

关于c# - 在VB.net/C#中直接使用资源字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2928383/

相关文章:

c# - 如何访问列表框中所选项目的属性并将其粘贴到文本框中

c# - 最小化的应用程序显示在任务栏上方

c# - 它在页面后面的 ASP.NET 代码中使用多种语言是否可以接受?

html - 替换为 HTML ascii 码

winforms - 在 Visual Studio 2010 中缺少 VB6 的 shift-click 添加工具箱项

java - 如何检测互联网访问?

c# - 是否可以将 vb6 "Val()"转换为 c#?

c# - WPF 和 C# : Trouble with Classes and Interfaces

c# - ASP.NET 5 中所有类型的 http header 都去了哪里?

c# - 生成逗号分隔值