2014-01-06 31 views
1

当我尝试在VS2012中运行以下代码段时,它会按预期安装字体。然而,当我开始应用从Windows资源管理器,它返回以下错误:“无法安装所需的字体:系统找不到指定的文件”无法安装字体

class Program 
{ 
    [DllImport("gdi32.dll", EntryPoint = "AddFontResourceW", SetLastError = true)] 
    public static extern int AddFontResource([In][MarshalAs(UnmanagedType.LPWStr)] 
            string lpFileName); 
    static void Main(string[] args) 
    { 
     string spath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\lucon.ttf"; 
     int result = AddFontResource(spath); 
     int error = Marshal.GetLastWin32Error(); 
     if (error != 0) 
     { 
      Console.WriteLine("Unable to install needed font: "+ new Win32Exception(error).Message); 
      Console.ReadKey(); 
     } 
     else 
     { 
      Console.WriteLine((result == 0) ? "Font is already installed." : "Font installed successfully."); 
     } 
    } 
} 

的lucon.ttf是在正确的文件夹。有人可以解释这一点,并帮助我从Windows资源管理器启动控制台应用程序时运行它吗?

回答

2

您的错误处理已损坏。一般Windows不会而不是当函数没有失败时重置最后的错误。此外,AddFontResource()是特殊的,它不会而不是设置最后一个错误,请检查MSDN文章。否则GDI函数的常见行为。所以,你必须做这样的:

int result = AddFontResource(spath); 
    if (result == 0) { 
     Console.WriteLine("Unable to install needed font"); 
     Console.ReadKey(); 
    } 

还不如修复PInvoke的声明:

[DllImport("gdi32.dll", CharSet = CharSet.Auto)] 
    public static extern int AddFontResource(string lpFileName); 
+0

三江源,是工作 – edepperson