2012-11-23 20 views
3

我試圖使用下面的代碼使用C#代碼安裝字體。即使在Windows重新啓動後,C#AddFontResource仍無法正常工作

調用InstallFont不會拋出任何異常並返回1.我認爲這表示它已安裝字體。但是,字體不會出現在Windows Fonts文件夾或檢查InstalledFontCollection的已安裝字體列表中,也不會顯示在我的軟件中。我已嘗試安裝後重新啓動計算機,但它仍然不可用。

如果我通過在Windows資源管理器中雙擊來手動安裝文件,然後單擊安裝字體安裝而沒有問題。

我在Windows 7 64位操作系統上使用C#,Visual Studio 2010,Microsoft .NET Framework 4.0。

任何幫助將不勝感激。

非常感謝, 保羅

清單文件包括:

requestedExecutionLevel level="requireAdministrator" uiAccess="false" 

施藥代碼:

[DllImport("user32.dll")] 
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam); 
[DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)] 
public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)] string lpFileName); 

public static int InstallFont()   
{ 
    InstalledFontCollection ifc = new InstalledFontCollection(); 

    if (ifc.Families.Any(item => item.Name == "Arial Narrow")) 
     return 100; // Font already installed 

    string filename = @"C:\Users\username\Downloads\ARIALN.TTF"; 

    const int WM_FONTCHANGE = 0x001D; 
    const int HWND_BROADCAST = 0xffff; 

    int added = AddFontResource(filename); 
    SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0); 

    return added; 
} 
+0

您正在使用哪個版本的Windows? – jeroenh

+0

Windows 7家庭高級版64位服務包1 – user1085489

+0

您的代碼看起來不錯。這是一個長鏡頭,但由於它似乎是一個下載的文件,也許你需要在安裝字體之前「解除阻止」它? (Windows資源管理器 - >屬性 - >解除阻止)? – jeroenh

回答

6

一定要看看MSDN庫文章AddFontResource():

此函數僅爲當前會話安裝字體。系統重新啓動時,字體不會顯示。即使在重新啓動系統後也要安裝字體,字體必須列在註冊表中。

InstalledFontCollection類僅枚舉實際安裝的字體並省略臨時字體。編寫註冊表項並將文件複製到c:\ windows \ fonts是非常安裝程序的職責。除了通過控制面板小程序之外,Microsoft不記錄如何執行此操作。如果您想對其進行註冊,註冊表項是HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Fonts

相關問題