Friday, June 26, 2009

How to embed a True Type font in using C#

 
It is easy to use any true type font in your application without installing.

Example: using C#


1) Create new project (myFont).
2) Create label(lblUsemyFontName).
3) Add your font file (myFontName.ttf) to Resources


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Text;

namespace myFont
{
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("gdi32.dll")]

private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont,uint cbFont,
IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

private PrivateFontCollection MYpfc = new PrivateFontCollection();

public Form1()
{
InitializeComponent();
try
{
unsafe
{
fixed (byte* pFontData = Properties.Resources.myFontName)
{
uint dummy = 0;
MYpfc.AddMemoryFont((IntPtr)pFontData, Properties.Resources.myFontName.Length);
AddFontMemResourceEx((IntPtr)pFontData, (uint)Properties.Resources.myFontName.Length, IntPtr.Zero, ref dummy);
}
}
}
catch
{
MessageBox.Show("Font does not correctly appear");

}
}

private void Form1_Load(object sender, EventArgs e)
{
lblUsemyFontName.Font = new Font(MYpfc.Families[0], 36); //Font size is 36
//lblUsemyFontName1.Font = new Font(MYpfc.Families[0], 22);//Font size is 22
// lblUsemyFontName2.Font = new Font(MYpfc.Families[0], 16);//Font size is 16
}
}
}


Now Your labels text displayed your font....