gdi32.dll AddFontResource在Visual Studio测试中给出错误代码1008

时间:2019-05-12 09:21:50

标签: c# windows visual-studio fonts

我需要向Windows系统添加临时字体。创建的名为FontManager的类使用“ gdi32.dll”,但不幸的是,由于错误代码1008,程序测试失败,并带有以下消息“试图引用不存在的令牌”。

我尝试在管理代码中打开Visual Studio代码并在Windows上禁用UAC控件。

 public class FontManager
{
    [System.Runtime.InteropServices.DllImport("gdi32", EntryPoint = "AddFontResource")]
    public static extern int AddFontResourceA(string lpFileName);
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    private static extern int AddFontResource(string lpszFilename);
    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    private static extern int CreateScalableFontResource(uint fdwHidden, string
    lpszFontRes, string lpszFontFile, string lpszCurrentPath);
    [DllImport("gdi32.dll", EntryPoint = "RemoveFontResourceW", SetLastError = true)]
    public static extern int RemoveFontResource([In][MarshalAs(UnmanagedType.LPWStr)]
                                        string lpFileName);



    public int  loadFont(String path)
    {
        int result = -1;
        int error = 0;
        result = AddFontResource(path);
        error = Marshal.GetLastWin32Error();

        if (error != 0)
        {
            Console.WriteLine(new Win32Exception(error).Message);
        }
        else
        {
            Console.WriteLine((result == 0) ? "Font was not found." :
                                              "Font removed successfully.");
        }
        return error; 

    }
}

测试是

[TestClass()]
public class FontManagerTests
{
    [TestMethod()]
    public void loadFontTest()
    {
        // setup 
        String path = Path.Combine("c:\\","Users" , "admin" , "Documents" , "Morphine Personal Use.ttf");
        Console.WriteLine(path);
        Assert.IsTrue(File.Exists(path));

        // when  
        FontManager fontManager = new FontManager();
        int error = fontManager.loadFont(path);
        Console.Write("error values " + error);
        // then 
        Assert.IsTrue(error == 0);


    }
}

0 个答案:

没有答案