C#:在文本框上使用嵌入字体 [英] C# : Using an embedded font on a textbox
问题描述
我将字体作为嵌入资源嵌入到我的 windows 窗体应用程序中,并希望在 TextBox
中使用它.
I'm embedding a font in my windows forms application as embedded resource, and want to use it in a TextBox
.
AddMemoryFont()
的帮助说我必须将兼容文本渲染设置为 true
才能使用 GDI+,这样我的字体就可以使用了.但不知何故,它只是无法显示正确的字体.
The help of AddMemoryFont()
says I have to set compatible text rendering to true
in order to use GDI+, and so my font can then be used. But somehow it just won't display the right font.
在 Program.cs 中我明确声明:
In Program.cs I explicitly state:
Application.SetCompatibleTextRenderingDefault(true);
为什么它不起作用?有人知道如何为 TextBox 设置自定义字体吗?
So why is it not working? Anybody got a clue on how to set a custom font to a TextBox?
推荐答案
好的,多亏了互联网和 Google,我才搞清楚.
Okay, I figured it out thanks to the interwebs and Google.
为了将来参考,如果有人遇到这个问题,修复方法是:在将嵌入的字体作为流获取之后,在调用 AddMemoryFont 之前,你必须调用 AddFontMemResourceEx !(在 C# 中不可用,因此您必须导入它:
For future reference, if anybody has this problem, the fix is : after getting your embedded font as a stream, and before calling AddMemoryFont, you have to call AddFontMemResourceEx ! (Not available in C# so you have to import it :
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);
然后:
//create an unsafe memory block for the data
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
//create a buffer to read in to
Byte[] fontData = new Byte[fontStream.Length];
//fetch the font program 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);
// We HAVE to do this to register the font to the system (Weird .NET bug !)
uint cFonts = 0;
AddFontMemResourceEx(data, (uint)fontData.Length, IntPtr.Zero, ref cFonts);
//pass the font to the font collection
mFontCollection.AddMemoryFont(data, (int)fontStream.Length);
//close the resource stream
fontStream.Close();
//free the unsafe memory
Marshal.FreeCoTaskMem(data);
而且很快,您将能够使用该字体.如果没有 AddFontMemResourceEx,它将无法工作.
And presto, you'll be able to use the font. Without the AddFontMemResourceEx it wont work.
这篇关于C#:在文本框上使用嵌入字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!