2013-02-10 57 views
9

如何使用C#安装字体?如何使用C#安装Windows字体#

我尝试使用File.Copy()复制字体,但由于访问权限限制(UnauthorizedException),我不允许我使用。

我该怎么办?

+2

我敢肯定,在安装新字体不仅仅包括文件的应对到Fonts文件夹了。 – dtb 2013-02-10 09:08:57

+0

提升应用程序运行的权限是否解决问题? – abatishchev 2013-02-10 09:26:44

+1

你应该问一个不同的问题:“如何安装字体?”。您现有的问题有一个微不足道的答案:您的用户没有访问权限。这个答案对你没有帮助。 – usr 2013-02-10 09:28:33

回答

18

您需要安装字体的其他方法。

  • 使用安装程序(创建一个安装项目)安装的字体
  • 使用本机方法的另一个(更容易)的方法。

声明DLL导入:

[DllImport("gdi32.dll", EntryPoint="AddFontResourceW", SetLastError=true)] 
    public static extern int AddFontResource(
     [In][MarshalAs(UnmanagedType.LPWStr)] 
     string lpFileName); 

在您的代码:

// Try install the font. 
    result = AddFontResource(@"C:\MY_FONT_LOCATION\MY_NEW_FONT.TTF"); 
    error = Marshal.GetLastWin32Error(); 

来源:

http://www.brutaldev.com/post/2009/03/26/Installing-and-removing-fonts-using-C

我把它一起在一个单元测试,我希望这有助于:

[TestFixture] 
public class Tests 
{ 
    // Declaring a dll import is nothing more than copy/pasting the next method declaration in your code. 
    // You can call the method from your own code, that way you can call native 
    // methods, in this case, install a font into windows. 
    [DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)] 
    public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)] 
            string lpFileName); 

    // This is a unit test sample, which just executes the native method and shows 
    // you how to handle the result and get a potential error. 
    [Test] 
    public void InstallFont() 
    { 
     // Try install the font. 
     var result = AddFontResource(@"C:\MY_FONT_LOCATION\MY_NEW_FONT.TTF"); 
     var error = Marshal.GetLastWin32Error(); 
     if (error != 0) 
     { 
      Console.WriteLine(new Win32Exception(error).Message); 
     } 
    } 
} 

这将有助于你对你的方式:)

+0

你能解释更多关于“声明dll导入:”bcuz我是新来的c# – 2013-02-10 09:43:23

+0

@ShahinRahbar你成功了吗?您不必事先接受答案。如果您对此感到满意,请提出答案,在您的问题真正解决时接受答案。只要让我知道你什么时候得到它,如果没有,我会尽力帮助 – bas 2013-02-10 09:55:09

+1

我没有rep upvote ...它编译正确,但字体不安装 – 2013-02-10 10:14:17

1
internal static void InstalarFuente(string NombreFnt,string RutaFnt) 
    { 
     string CMD = string.Format("copy /Y \"{0}\" \"%WINDIR%\\Fonts\" ", RutaFnt); 
     EjecutarCMD(CMD); 

     System.IO.FileInfo FInfo = new System.IO.FileInfo(RutaFnt); 
     CMD = string.Format("reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts\" /v \"{0}\" /t REG_SZ /d {1} /f", NombreFnt, FInfo.Name); 
     EjecutarCMD(CMD); 
    } 

    public static void EjecutarCMD(string Comando) 
    { 
     System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo("cmd.exe"); 
     Info.Arguments = string.Format("/c {0}", Comando); 
     Info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
     System.Diagnostics.Process.Start(Info); 
    } 
+0

注销考虑字体 – JxDarkAngel 2014-10-09 17:39:08