-
Notifications
You must be signed in to change notification settings - Fork 951
/
PrivateFontCollection.cs
92 lines (80 loc) · 2.74 KB
/
PrivateFontCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
namespace System.Drawing.Text;
/// <summary>
/// Encapsulates a collection of <see cref='Font'/> objects.
/// </summary>
public sealed unsafe class PrivateFontCollection : FontCollection
{
/// <summary>
/// Initializes a new instance of the <see cref='PrivateFontCollection'/> class.
/// </summary>
public PrivateFontCollection() : base()
{
GpFontCollection* fontCollection;
PInvoke.GdipNewPrivateFontCollection(&fontCollection).ThrowIfFailed();
_nativeFontCollection = fontCollection;
}
/// <summary>
/// Cleans up Windows resources for this <see cref='PrivateFontCollection'/>.
/// </summary>
protected override void Dispose(bool disposing)
{
if (_nativeFontCollection is not null)
{
GpFontCollection* nativeFontCollection = _nativeFontCollection;
try
{
#if DEBUG
Status status = !Gdip.Initialized ? Status.Ok :
#endif
PInvoke.GdipDeletePrivateFontCollection(&nativeFontCollection);
#if DEBUG
Debug.Assert(status == Status.Ok, $"GDI+ returned an error status: {status}");
#endif
}
catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex))
{
}
finally
{
_nativeFontCollection = null;
}
}
base.Dispose(disposing);
}
/// <summary>
/// Adds a font from the specified file to this <see cref='PrivateFontCollection'/>.
/// </summary>
public void AddFontFile(string filename)
{
ArgumentNullException.ThrowIfNull(filename);
if (!File.Exists(filename))
{
throw new FileNotFoundException();
}
fixed (char* p = filename)
{
PInvoke.GdipPrivateAddFontFile(_nativeFontCollection, p).ThrowIfFailed();
GC.KeepAlive(this);
}
// Register private font with GDI as well so pure GDI-based controls (TextBox, Button for instance) can access it.
GdiAddFontFile(filename);
}
/// <summary>
/// Adds a font contained in system memory to this <see cref='PrivateFontCollection'/>.
/// </summary>
public void AddMemoryFont(IntPtr memory, int length)
{
PInvoke.GdipPrivateAddMemoryFont(_nativeFontCollection, (void*)memory, length).ThrowIfFailed();
GC.KeepAlive(this);
}
private static void GdiAddFontFile(string filename)
{
fixed (char* fn = filename)
{
PInvoke.AddFontResourceEx(fn, FONT_RESOURCE_CHARACTERISTICS.FR_PRIVATE);
}
}
}