2010-12-16 78 views
0

已將TrueType字體添加到我的項目資源(「MyFontResource」)中,並且已將生成操作設置爲「Resource」。我的意圖是用這個資源替換Label對象上的字體。Windows窗體:無法正確顯示字體資源

這裏是我的代碼:

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的字體。

現在呢?

回答

3

沒關係,發現原因這不起作用here

這裏是一個有效的解決方案(原代碼here):

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); 
    } 
} 
+0

看起來很熟悉。 – 2010-12-16 21:37:07

+0

謝謝,你的代碼讓我不必記住VB。 – 2012-05-18 19:04:38