好吧,在基于之前收到的 cmets 进行了大量 SO 和 Google 之后,我能够将字体嵌入到我的代码中。现在,在启动时,我的应用程序会检查机器上是否安装了字体。如果没有安装字体,我的应用会安装它。
这种方式无需手动检查字体是否安装在将运行应用程序的每台机器上。
注意:需要管理员权限才能工作。
首先:将字体文件作为资源嵌入
- 双击 Resources.resx,然后在设计器的工具栏中单击添加资源/添加现有文件并选择您的 .ttf 文件
- 在解决方案资源管理器中,右键单击您的 .ttf 文件并转到“属性”。将“构建操作”设置为“内容”,将“复制到输出目录”属性设置为“始终复制”
第二:添加这段代码
using Microsoft.Win32;
using System;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace TestAutomation
{
public partial class SplashScreen : Form
{
[DllImport("gdi32.dll", EntryPoint = "AddFontResource")]
public static extern int AddFontResource(string lpFileName);
[DllImport("gdi32.dll")]
private static extern int CreateScalableFontResource(uint fdwHidden, string
lpszFontRes, string lpszFontFile, string lpszCurrentPath);
// <summary>
// Installs font on the user's system and adds it to the registry so it's available on the next session
// Your font must be embedded as a resource in your project with its 'Build Action' property set to 'Content'
// and its 'Copy To Output Directory' property set to 'Copy Always'
// </summary>
private void RegisterFont(string contentFontName)
{
DirectoryInfo dirWindowsFolder = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.System));
// Concatenate Fonts folder onto Windows folder.
string strFontsFolder = Path.Combine(dirWindowsFolder.FullName, "Fonts");
// Creates the full path where your font will be installed
var fontDestination = Path.Combine(strFontsFolder, contentFontName);
// Check if file exists in destination folder. If not, then copy the file from project directory to destination
if (!File.Exists(fontDestination))
{
try
{
// Copies font to destination
File.Copy(Path.Combine(Directory.GetCurrentDirectory(), contentFontName), fontDestination);
// Retrieves font name
PrivateFontCollection fontCol = new PrivateFontCollection();
fontCol.AddFontFile(fontDestination);
var actualFontName = fontCol.Families[0].Name;
// Add font
AddFontResource(fontDestination);
// Add registry entry
Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",
actualFontName, contentFontName, RegistryValueKind.String);
}
catch (Exception e)
{
MessageBox.Show(e.Message + "\n\nThe required font(s) have not been installed."
+ "\n\nPlease contact your systems administrator for help.");
Start();
}
}
// If file exists in destination folder, then start program.
else
{
Start();
}
}
public SplashScreen()
{
RegisterFont("GOTHIC.TTF");
}
private void Start()
{
InitializeComponent();
}
}
}
我修改了代码以满足我的需要。以下是我找到我的信息的链接:
How to quickly and easily embed fonts in winforms app in C#
https://csharp.hotexamples.com/examples/System.Drawing.Text/PrivateFontCollection/AddFontFile/php-privatefontcollection-addfontfile-method-examples.html