Font Installation und Abfrage unter .NET
Frank Dzaebel, erstellt am: 23.12.2005, zuletzt geändert: 23.12.2005
Kategorie:Fonts, .NET-Version:2.0, [Download]
Dieses Codebeispiel zeigt eine Möglichkeit auf, einen eigenen Font zu installieren oder abzurufen. In diesem Fall "aerosol.ttf". Die zentralen Bausteine dabei sind die PrivateFontCollection und die InstalledFontCollection:
[DllImport("gdi32", CharSet=CharSet.Auto)]
private static extern int AddFontResource(string lpszFilename);
[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd,uint Msg, int wParam, int lParam);
const int HWND_BROADCAST = 0xFFFF;
const int WM_FONTCHANGE = 0x1D;
private void btnCheckInstall_Click(object sender,EventArgs e)
{
string fntName = "aerosol.ttf";
string fntPath = Path.GetFullPath(Application.StartupPath +
"/../../" + fntName);
bool installiert = FontIsInstalled(fntPath);
if (!installiert) InstallFont(fntPath);
}
private bool FontIsInstalled(string fntPath)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(fntPath);
string fntName = ((FontFamily)pfc.Families.GetValue(0)).Name;
InstalledFontCollection ifc = new InstalledFontCollection();
foreach (FontFamily ff in ifc.Families)
if (ff.Name == fntName) return true;
return false;
}
private void InstallFont(string fntPath)
{
string fntName = Path.GetFileName(fntPath);
AddFontResource(fntPath);
string windir = Environment.GetEnvironmentVariable("windir");
string fontDir = Path.Combine(windir,"Fonts");
string fntTarget = Path.Combine(fontDir,Path.GetFileName(fntPath));
File.Copy(fntPath,fntTarget,true);
RegistryKey reg = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",true);
string subkey = fntName.Split('.')[0] + " (TrueType)";
reg.SetValue(subkey,fntName); reg.Close();
SendMessage(HWND_BROADCAST,WM_FONTCHANGE,0,0);
}