在所有表单中使用嵌入字体 [英] using embedded font in all forms

查看:88
本文介绍了在所有表单中使用嵌入字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个类来嵌入字体

Hi,I used this class to embed a font

public static class theFont
    {
        [DllImport("gdi32.dll")]
        private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont, IntPtr pdv, [In] ref uint pcFonts);
       static FontFamily ff;
       static Font font;

        public static Font CargoPrivateFontCollection(float size,FontStyle style)
        {
            // Create the byte array and get its length

            byte[] fontArray = Salary.Properties.Resources.MyFont;
            int dataLength = Salary.Properties.Resources.MyFont.Length;


            // ASSIGN MEMORY AND COPY  BYTE[] ON THAT MEMORY ADDRESS
            IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
            Marshal.Copy(fontArray, 0, ptrData, dataLength);


            uint cFonts = 0;
            AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);

            PrivateFontCollection pfc = new PrivateFontCollection();
            //PASS THE FONT TO THE  PRIVATEFONTCOLLECTION OBJECT
            pfc.AddMemoryFont(ptrData, dataLength);

            //FREE THE  "UNSAFE" MEMORY
            Marshal.FreeCoTaskMem(ptrData);

            ff = pfc.Families[0];
           return font = new Font(ff,size, style);
        }
    }



我将在表单中的所有控件中使用此字体,因此我尝试将下面的代码放在Load事件中表格和UC


I'm going to use this font in all Controls in forms so I tried to put below code in Load event of all Forms and UCs

/////////////Font///////////
   foreach (Control cx in this.Controls)
       cx.Font = theFont.CargoPrivateFontCollection(9f, FontStyle.Regular);



但是Program.cs中的这个错误发生了


but this error in Program.cs happend

"system.drawing.Graphics Object is currently in use elsewhere"





有什么问题?



What's the problem?

推荐答案

使用P / Invoke这是一个非常糟糕的主意,因为它可以完全打破这个强大的平台兼容性CLR提供。为何与资源一起使用?在程序集的模块中嵌入了.NET资源;它们可以完美地用于绝对任何类型的资源,包括任何自定义数据,无论数据格式如何。



关于嵌入字体,这在这里得到很好的证明CodeProject文章:

将字体嵌入资源 [ ^ ]。



-SA
This is a really bad idea to use P/Invoke where it is not absolutely needed, because it can totally break that powerful platform compatibility CLR provides. Why using it with resources? There are .NET resources embedded in the module of an assembly; they work perfectly for absolutely any kind of resources, including any custom data, regardless of the data format.

As to the embedding of fonts, this is well demonstrated in this CodeProject article:
Embedding Font To Resources[^].

—SA


先生,如果你正确调试,你会看到错误是从名为theFont的类生成的。尝试使用尝试捕捉来检查错误产生的位置。
sir, if you debug it correctly you will see the error is generated from that class named "theFont" . Try using "try catch" to check where is the error generating.


这篇关于在所有表单中使用嵌入字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆