PrivateFontCollection
Provides a collection of font families built from font files that are provided by the client application.
using System.IO;
using System.Runtime.CompilerServices;
using Windows.Win32;
using Windows.Win32.Graphics.Gdi;
using Windows.Win32.Graphics.GdiPlus;
namespace System.Drawing.Text
{
[NullableContext(1)]
[Nullable(0)]
public sealed class PrivateFontCollection : FontCollection
{
public unsafe PrivateFontCollection()
{
GpFontCollection* nativeFontCollection = default(GpFontCollection*);
PInvoke.GdipNewPrivateFontCollection(&nativeFontCollection).ThrowIfFailed();
_nativeFontCollection = nativeFontCollection;
}
protected unsafe override void Dispose(bool disposing)
{
if (_nativeFontCollection != null) {
GpFontCollection* nativeFontCollection = _nativeFontCollection;
try {
PInvoke.GdipDeletePrivateFontCollection(&nativeFontCollection);
} catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) {
} finally {
_nativeFontCollection = null;
}
}
base.Dispose(disposing);
}
public unsafe void AddFontFile(string filename)
{
ArgumentNullException.ThrowIfNull(filename, "filename");
if (!File.Exists(filename))
throw new FileNotFoundException();
IntPtr intPtr;
if (filename == null)
intPtr = (IntPtr)(void*)null;
else {
ref reference = ref filename.GetPinnableReference();
intPtr = (IntPtr)(&reference);
}
char* value = (char*)(long)intPtr;
PInvoke.GdipPrivateAddFontFile(_nativeFontCollection, value).ThrowIfFailed();
GC.KeepAlive(this);
ref reference = ref *(char*)null;
GdiAddFontFile(filename);
}
public unsafe void AddMemoryFont(IntPtr memory, int length)
{
PInvoke.GdipPrivateAddMemoryFont(_nativeFontCollection, (void*)(long)memory, length).ThrowIfFailed();
GC.KeepAlive(this);
}
private unsafe static void GdiAddFontFile(string filename)
{
IntPtr value;
if (filename == null)
value = (IntPtr)(void*)null;
else {
ref reference = ref filename.GetPinnableReference();
value = (IntPtr)(&reference);
}
PInvoke.AddFontResourceEx((char*)(long)value, FONT_RESOURCE_CHARACTERISTICS.FR_PRIVATE, null);
ref reference = ref *(char*)null;
}
}
}