1. 程式人生 > 程式設計 >windows系統下,如何在C#程式中自動安裝字型

windows系統下,如何在C#程式中自動安裝字型

  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); 
       //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,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、#動態載入和解除安裝字型(以檔案的方式)
因為是在CE裡,所以是用Coredll PC機用的不是這個,可查MSDN

[System.Runtime.InteropServices.DllImport("coredll",EntryPoint = "AddFontResource")]
 private static extern int AddFontResource([In,MarshalAs(UnmanagedType.LPWStr)]string fontSource);

 [DllImport("coredll",EntryPoint = "SendMessage")]
 private static extern int SendMessage(IntPtr hWnd,int Msg,IntPtr wParam,IntPtr lParam);
 private void Fun()
 {
   int installFont = AddFontResource(@"/SDMEM/MSYH.TTF"); //這是字型的安裝 返回不為0即成功
   SendMessage((IntPtr)0xffff,0x001d,IntPtr.Zero,IntPtr.Zero); //通知其它正在執行的應用程式,有新字型註冊了           
   InstalledFontCollection enumFonts = new InstalledFontCollection();
   FontFamily[] fonts = enumFonts.Families;
   foreach (FontFamily font in fonts)
   {
     MessageBox.Show(font.Name);
   }
 }

  2、檢測系統中是否包含某種字型

  對於檢測是否已經安裝了某種字型的方法有很多,這裡只介紹檢測是否有該檔案的方式:

/// <summary>
/// 檢查字型是否存在
/// </summary>
/// <param name="familyName">字型名稱</param>
/// <returns></returns>
public static bool CheckFont(string familyName)
{
  string FontPath = Path.Combine(System.Environment.GetEnvironmentVariable("WINDIR"),Path.GetFileName(familyName));
  //檢測系統是否已安裝該字型
  return File.Exists(FontPath);
}

  檢測某種字型樣式是否可用:

/// <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;
}

以上就是windows系統下,如何在C#程式中自動安裝字型的詳細內容,更多關於c# 安裝字型的資料請關注我們其它相關文章!