Search code examples
c#compact-frameworkwindows-ce.net-2.0smart-device

How to use AddFontResource in c# for Windows CE 5.0 application with .NET CF2.0


I'm trying to develop a Smart Device program for Windows CE 5.0 device in my car with Visual Studio 2008 pro and c# with .NET CF2.0. I want to add a font using AddFontResourceEx, but I can't get it to work. Here is the code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private const uint FR_PRIVATE=0x10;
    
    [DllImport("GDI32.dll",EntryPoint="AddFontResourceEx")]
        static extern int AddFontResourceEx(string lpszFilename, uint fl, IntPtr pdv);
        
    private void button1_Click(object sender, EventArgs e)
    {
        AddFontResourceEx(".\\ELEPHNT.TTF", FR_PRIVATE, IntPtr.Zero);
        label1.ForeColor = Color.FromArgb(155, 25, 34);
        label1.Font = new Font("ELEPHNT.TTF", 18, FontStyle.Regular);
        label1.Text = "Hello world!";
    }
}

Button1 and label1 were added in the Designer. It builds succesfully and I can run the program, but the font won't change. I added the font file to the same directory where the program is. Could you please tell me what is wrong?

EDIT: Valter Minute helped me on my way and for those who want to know, here is the right code:


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    
    private const uint FR_PRIVATE=0x10;
        
    [DllImport("coredll.dll",EntryPoint="AddFontResourceW")]
        private static extern int AddFontResource(string lpszFilename, uint fl, IntPtr pdv);
    
    string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

   
    private void button1_Click(object sender, EventArgs e)
    {
        AddFontResource(path + "\\ELEPHNT.TTF", FR_PRIVATE, IntPtr.Zero);
        label1.ForeColor = Color.FromArgb(155, 25, 34);
        label1.Font = new Font("Elephant", 18, FontStyle.Regular);
        label1.Text = "Hello world!";
    }
}

The above code works in a CE device that can handle true type fonts (.TTF). Some other CE devices (like the one in my car) use raster (bitmap) fonts (eg .FNT type fonts). In that case you can convert the .TTF font file to a .FNT font file using a program like FontForge.


Solution

  • You can't use a C++ declaration inside C# code, you need to use pinvoke and compatible data types: http://www.pinvoke.net/search.aspx?search=addfontresource&namespace=[All] In Windows CE there is no relative path, so you'll have to use the full path of your font file, starting from .