Hi, In a previous post, I explained you how to embed a ttf file into the .exe file and loading it to the window form using Visual C# or Microsoft Visual Studio.
Now I am going to explain you how you can load the font file directly at runtime, without the need of adding the .ttf or any other type of file to the resources.
Let's take a quick look at what are we going to do:
1- Create a Windows Form Application
2 - Add the System.IO namespace and the System.Drawing.Text namespac
- using System.IO;
- using System.Drawing.Text;
3 - Add a Label to the window form for displaying purposes.
Now, I will load the file in the Load Event just to be quick with this. So add the Load event to the form.
If you don't know how to do this, just double click the Window Bar of your window preview.
I am going to create a Method called LoadFontFamily that returns a FontFamily and is private.
private FontFamily LoadFontFamily(string fileName, out PrivateFontCollection _myFonts)
//IN MEMORY _myFonts point to the myFonts created in the load event 11 lines up.
_myFonts = new PrivateFontCollection();//here is where we assing memory space to myFonts
_myFonts.AddFontFile(fileName);//we add the full path of the ttf file
return _myFonts.Families;//returns the family object as usual.
}//NOW THE LOAD EVENT WHERE WE ARE GOING TO MAKE THE CALL TO THIS METHOD AND MODIFY THE LABEL.FONT PROPERTY TO USE OWR FONT
private void Form1_Load_1(object sender, EventArgs e)
PrivateFontCollection myFonts; //CREATE A FONT COLLECTION
//CREATES A FONTFAMILY
//(LOOK THE out word in the parameter sent to the method, that will modify myFonts object)
FontFamily family = LoadFontFamily(@"C:\Downloads\Backlog Normal.ttf", out myFonts);
//CREATES A FONT FOR LATER USE
Font theFont = new Font(family, 20.0f);
//HERE WE SET THE LABEL FONT PROPERTY TO THE ONE WE JUST LOADED
label1.Font = theFont;
label1.Text = "HELLO WORLD!";
Have a nice day.