C# Windows窗体:Can';无法正确显示字体资源
我已经将TrueType字体添加到我的项目资源(“MyFontResource”),并且我已经将构建操作设置为“Resource”。我的目的是用此资源替换标签对象上的字体 这是我的密码:C# Windows窗体:Can';无法正确显示字体资源,c#,winforms,resources,fonts,privatefontcollection,C#,Winforms,Resources,Fonts,Privatefontcollection,我已经将TrueType字体添加到我的项目资源(“MyFontResource”),并且我已经将构建操作设置为“Resource”。我的目的是用此资源替换标签对象上的字体 这是我的密码: PrivateFontCollection myFonts = new PrivateFontCollection(); unsafe { fixed (byte* fontBytes = Properties.Resources.MyFontResource) myFonts.AddM
PrivateFontCollection myFonts = new PrivateFontCollection();
unsafe {
fixed (byte* fontBytes = Properties.Resources.MyFontResource)
myFonts.AddMemoryFont((IntPtr)fontBytes, Properties.Resources.MyFontResource.Length);
}
myLabel.Font = new Font(myFonts.Families[0], 10f);
只有在本地安装字体时,字体才会按预期显示。如果我没有安装字体,那么我会在我的C#项目中看到最初分配给myLabel的字体
现在怎么办?没关系,我找到了这不起作用的原因 下面是一个有效的解决方案(原始代码):
没关系,我找到了这不起作用的原因 下面是一个有效的解决方案(原始代码):
class MyClass {
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);
public MyClass() {
uint installCount = 1;
PrivateFontCollection myFonts = new PrivateFontCollection();
unsafe {
fixed (byte* pFontData = Properties.Resources.MyFont) {
myFonts.AddMemoryFont((IntPtr)pFontData, Properties.Resources.MyFont.Length);
AddFontMemResourceEx((IntPtr)pFontData, (uint)Properties.Resources.MyFont.Length, IntPtr.Zero, ref installCount);
}
}
myLabel.Font = new Font(myFonts.Families[0], 20f);
}
}