在Windows系統中,原有自帶的字體樣式有限,有時候我們的程序會使用到個別稀有或系統不自帶的字體。因此我們需要將字體打包到程序中,當程序啓動時,檢測系統是否有該字體,如果沒有則安裝該字體,也可以動態加載字體。
1.1、使用代碼安裝字體
注意:安裝字體時,需要windows的管理員權限。
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);
[DllImport("gdi32")]
public static extern int AddFontResource(string lpFileName);
/// <summary>
/// 安裝字體
/// </summary>
/// <param name="fontFilePath">字體文件全路徑</param>
/// <returns>是否成功安裝字體</returns>
/// <exception cref="UnauthorizedAccessException">不是管理員運行程序</exception>
/// <exception cref="Exception">字體安裝失敗</exception>
public static bool InstallFont(string fontFilePath)
{
try
{
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判斷當前登錄用戶是否爲管理員
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) == false)
{
throw new UnauthorizedAccessException("當前用戶無管理員權限,無法安裝字體。");
}
//獲取Windows字體文件夾路徑
string fontPath=Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR") , "fonts",Path.GetFileName(fontFilePath));
//檢測系統是否已安裝該字體
if (!File.Exists(fontPath))
{
// File.Copy(System.Windows.Forms.Application.StartupPath + "\\font\\" + FontFileName, FontPath); //font是程序目錄下放字體的文件夾
//將某路徑下的字體拷貝到系統字體文件夾下
File.Copy(fontFilePath, fontPath); //font是程序目錄下放字體的文件夾
AddFontResource(fontPath);
//Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
//WIN7下編譯會出錯,不清楚什麼問題。註釋就行了。
//安裝字體
WriteProfileString("fonts", Path.GetFileNameWithoutExtension(fontFilePath) + "(TrueType)", Path.GetFileName(fontFilePath));
}
}
catch (Exception ex)
{
throw new Exception(string.Format($"[{Path.GetFileNameWithoutExtension(fontFilePath)}] 字體安裝失敗!原因:{ex.Message}" ));
}
return true;
}
1.2、從項目資源文件中加載字體
該方法需要開發者將字體文件以資源的形式放入項目資源文件中。不用安裝到字體庫中,其他程序如果需要使用,就需要自己安裝或者加載。此時可以使用以下代碼創建程序所需字體:
/// <summary>
/// 如何使用資源文件中的字體,無安裝無釋放
/// </summary>
/// <param name="bytes">資源文件中的字體文件</param>
/// <returns></returns>
public Font GetResoruceFont(byte[] bytes)
{
System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
IntPtr MeAdd = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, MeAdd, bytes.Length);
pfc.AddMemoryFont(MeAdd, bytes.Length);
return new Font(pfc.Families[0], 15, FontStyle.Regular);
}
1.3、加載某個字體文件,加載字體
設置好某個字體的路徑,然後加載字體文件,從而創建字體。不用安裝到字體庫中,其他程序如果需要使用,就需要自己安裝或者加載。
/// <summary>
/// 通過文件獲取字體
/// </summary>
/// <param name="filePath">文件全路徑</param>
/// <returns>字體</returns>
public Font GetFontByFile(string filePath)
{
//程序直接調用字體文件,不用安裝到系統字庫中。
System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
pfc.AddFontFile(filePath);//字體文件的路徑
Font font = new Font(pfc.Families[0], 24, FontStyle.Regular, GraphicsUnit.Point, 0);//font就是通過文件創建的字體對象
return font;
}
1.4、檢測系統中是否包含某種字體
對於檢測是否已經安裝了某種字體的方法有很多,這裏只介紹檢測是否有該文件的方式:
/// <summary>
/// 檢查字體是否存在
/// </summary>
/// <param name="familyName">字體名稱</param>
/// <returns></returns>
public static bool CheckFont(string familyName)
{
string FontPath = Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR"), "fonts", Path.GetFileName(familyName));
//檢測系統是否已安裝該字體
return File.Exists(FontPath);
}
1.5、檢測某種字體樣式是否可用
/// <summary>
/// 檢測某種字體樣式是否可用
/// </summary>
/// <param name="familyName">字體名稱</param>
/// <param name="fontStyle">字體樣式</param>
/// <returns></returns>
public bool CheckFont(string familyName, FontStyle fontStyle= FontStyle.Regular )
{
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
FontFamily[] fontFamilies = installedFontCollection.Families;
foreach(var item in fontFamilies)
{
if (item.Name.Equals(familyName))
{
return item.IsStyleAvailable(fontStyle);
}
}
return false;
}