2009-12-23 87 views
8

我在嵌入式資源中嵌入字體,並希望在文本框中使用它。 AddMemoryFont幫助說我必須設置兼容的文字渲染爲真使用GDI +,所以我的字體可以使用,但不知何故,它只是不會顯示正確的字體。C#:在文本框中使用嵌入字體

在Program.cs中我明確指出: Application.SetCompatibleTextRenderingDefault(true);

那麼,爲什麼它不工作? 有人有線索嗎?

回答

19

好的,我想通過interwebs和Google來解決這個問題。

以供將來參考,如果任何人有這個問題,解決方法是: 讓你的嵌入字體作爲流後,並呼籲AddMemoryFont, 你必須調用AddFontMemResourceEx之前! (所以你必須導入它在C#中不可用:

[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它不會工作

+0

+1有用,知道,謝謝,Led – BillW 2009-12-24 07:15:50

+0

聖螃蟹我一直在撞我的頭靠在牆上數小時感謝!! – Mike 2014-01-16 18:46:53

+0

「fontStream」從哪裏來? – 2016-02-02 03:58:24