9

C# を使用してフォントをインストールするにはどうすればよいですか?

を使用してフォントをコピーしようとしましたFile.Copy()が、アクセス権の制限により許可されていません ( UnauthorizedException)。

私は何をすべきか?

4

2 に答える 2

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

それはあなたの途中であなたを助けるはずです:)

于 2013-02-10T09:17:36.023 に答える