C# 通过代码方式安装字体


安装字体辅助类

public class FontHelper
{
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);
    [DllImport("user32.dll")]
    public static extern int SendMessage(int hWnd, // handle to destination window 
    uint Msg, // message 
    int wParam, // first message parameter 
    int lParam // second message parameter 
    );
    [DllImport("gdi32")]
    public static extern int AddFontResource(string lpFileName);
    [DllImport("gdi32")]
    public static extern int RemoveFontResource(string lpFileName);

    /// <summary>
    /// 
    /// </summary>
    /// <param name="fontPath">字体全路径</param>
    /// <param name="fontName">字体名称</param>
    /// <returns></returns>
    public static int InstallFont(string fontPath, string fontFileName, string fontName)
    {
        string WinFontDir = "C:\\windows\\fonts";
        int Ret = 0;
        int Res;
        string targetPath;
        const int WM_FONTCHANGE = 0x001D;
        const int HWND_BROADCAST = 0xffff;
        targetPath = WinFontDir + "\\" + fontFileName;
        if (File.Exists(targetPath))//若已存在则先删除之
        {
            try
            {
                UnInstallFont(targetPath);
            }
            catch (Exception)
            {

                //throw;
            }
        }
        if (!File.Exists(targetPath))
        {
            File.Copy(fontPath, targetPath);
            Ret = AddFontResource(targetPath);
            Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
            //Ret =
            WriteProfileString("fonts", fontName + "(TrueType)", fontFileName);
        }
        return Ret;
    }

    public static int UnInstallFont(string FontFilePathName)
    {
        RemoveFontResource(FontFilePathName);
        try
        {
            File.Delete(FontFilePathName);
        }
        catch (Exception)
        {
            return 0;
        }
        return 1;
    }
}

调用方法

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            int resultCode = FontHelper.InstallFont("D:\\Fonts\\HelveticaNeueLight.otf", "HelveticaNeueLight.otf", "Helvetica Neue");
            if (resultCode == 1)
            {
                MessageBox.Show("安装成功");
                return;
            }
            MessageBox.Show("安装失败");
        }
        catch (Exception ex)
        {
            MessageBox.Show("安装失败:" + ex.Message);
        }
    }
}

知识共享许可协议
《C# 通过代码方式安装字体》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告