您可以将字体作为资源嵌入并使用unsafe 关键字(并且必须使用'unsafe'编译)来获取字体...这是我用来将用户控件设置为字体的示例代码输入“OCR”
私有 PrivateFontCollection pfc = new PrivateFontCollection();
私人字体_fntOCRFont = null;
私有枚举 FontEnum{
OCR = 0
};
这声明了一个私有的字体集合...字体'OCR'使用命名约定作为资源嵌入,其中'foo'是一个命名空间,因此资源名称将是'foo.ocraext.ttf'.. .看这里的“InitOCRFont”,它加载字体并将其添加到集合中:
私人无效InitOCRFont(){
尝试{
System.IO.Stream streamFont = this.GetType().Assembly.GetManifestResourceStream("foo.ocraext.ttf");
如果(流字体!= null){
byte[] fontData = new byte[streamFont.Length];
streamFont.Read(fontData, 0, (int)streamFont.Length);
streamFont.Close();
不安全{
固定(字节 *pFontData = fontData){
this.pfc.AddMemoryFont((System.IntPtr)pFontData, fontData.Length);
}
}
}别的{
throw new Exception("错误!无法读取内置字体。");
}
}catch(异常 eX){
throw new Exception("InitOCRFont 方法 - 发生异常!\n异常是:" + eX.Message);
}
}
在这里,我设置了用户控件中的控件,通过遍历集合将字体设置为“OCR”字体,参见“InitializeCtlFont”,字体大小为 10,并且是粗体“字体”:
私人无效 InitializeCtlFont(){
this._fntOCRFont = new Font(this.pfc.Families[0], 10.0F, System.Drawing.FontStyle.Bold);
if (this._fntOCRFont != null){
foreach(在 this.Controls 中控制 ctl){
if (ctl != null && ((ctl is Label) || (ctl is TextBox))){
ctl.Font = this._fntOCRFont;
}
}
}
}
当用户控件被释放时,必须释放字体占用的资源,如Dispose方法中所示:
尝试{
if (this._fntOCRFont != null) this._fntOCRFont.Dispose();
}抓住{
}
尝试{
if (this.pfc != null) this.pfc.Dispose();
}抓住{
}
希望这会有所帮助,
最好的祝福,
汤姆。