首页 > 解决方案 > 尝试从 VS 表单应用程序资源加载字体文件时出错

问题描述

ff = pfc.Families[0];在尝试从我的 VS 表单应用程序资源加载我的 .tff 字体文件时遇到了“IndexOutOfRangeException”。您认为您可以查看我的代码并告诉我为什么以及如何修复它?

public partial class MainForm : Form
{
        [DllImport("gdi32.dll")]
        private static extern IntPtr AddFontMemResourceEx(IntPtr pbfont, uint cbfont, IntPtr pdv, [In] ref uint pcFonts);

        FontFamily ff;
        Font font;

        bool NameFieldPopulated = false;
        bool TitleFieldPopulated = false;
        bool LocationFieldPopulated = false;
        bool ExtFieldPopulated = false;
        bool OutputFieldPopulated = false;
        public static string NameInput;
        public static string DirName;
        public static string TitleInput;
        public static string LocationInput;
        public static string PhoneNumber;
        public static string ExtensionInput;
        public static string DirInput;
        public Form2 overwrite;
        public SucessForm success;
        public OverwriteSucessForm succ2;
        public MainForm main;


        public MainForm()
        {
            InitializeComponent();
            GenerateButton.Enabled = false;
        }

        private void loadFont()
        {
            byte[] fontArray = SF_Signature_Generator.Properties.Resources.bignoodletitling;
            int dataLength = SF_Signature_Generator.Properties.Resources.bignoodletitling.Length;

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

            pfc.AddMemoryFont(ptrData, dataLength);

            Marshal.FreeCoTaskMem(ptrData);

            ff = pfc.Families[0];
            font = new Font(ff, 15f, FontStyle.Regular);

        }

        private void AllocFont(Font f, Control c, float size)
        {
            FontStyle fontStyle = FontStyle.Regular;

            c.Font = new Font(ff, size, fontStyle);
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            loadFont();
            AllocFont(font, this.NameLabel, 20);
        }
}

标签: c#visual-studio

解决方案


推荐阅读