/
Font.cs
751 lines (648 loc) · 26.3 KB
/
Font.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Drawing.Interop;
namespace System.Drawing;
/// <summary>
/// Defines a particular format for text, including font face, size, and style attributes.
/// </summary>
[Editor($"System.Drawing.Design.FontEditor, {AssemblyRef.SystemDrawingDesign}",
$"System.Drawing.Design.UITypeEditor, {AssemblyRef.SystemDrawing}")]
[TypeConverter(typeof(FontConverter))]
[Serializable]
[Runtime.CompilerServices.TypeForwardedFrom(AssemblyRef.SystemDrawing)]
public sealed unsafe class Font : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
private GpFont* _nativeFont;
private float _fontSize;
private FontStyle _fontStyle;
private FontFamily _fontFamily = null!;
private GraphicsUnit _fontUnit;
private byte _gdiCharSet = (byte)FONT_CHARSET.DEFAULT_CHARSET;
private bool _gdiVerticalFont;
private string _systemFontName = string.Empty;
private string? _originalFontName;
// Return value is in Unit (the unit the font was created in)
/// <summary>
/// Gets the size of this <see cref='Font'/>.
/// </summary>
public float Size => _fontSize;
/// <summary>
/// Gets style information for this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontStyle Style => _fontStyle;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is bold.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Bold => (Style & FontStyle.Bold) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is Italic.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Italic => (Style & FontStyle.Italic) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it).
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Strikeout => (Style & FontStyle.Strikeout) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is underlined.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Underline => (Style & FontStyle.Underline) != 0;
/// <summary>
/// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontFamily FontFamily => _fontFamily;
/// <summary>
/// Gets the face name of this <see cref='Font'/> .
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Editor($"System.Drawing.Design.FontNameEditor, {AssemblyRef.SystemDrawingDesign}",
$"System.Drawing.Design.UITypeEditor, {AssemblyRef.SystemDrawing}")]
[TypeConverter(typeof(FontConverter.FontNameConverter))]
public string Name => FontFamily.Name;
/// <summary>
/// Gets the unit of measure for this <see cref='Font'/>.
/// </summary>
[TypeConverter(typeof(FontConverter.FontUnitConverter))]
public GraphicsUnit Unit => _fontUnit;
/// <summary>
/// Returns the GDI char set for this instance of a font. This will only
/// be valid if this font was created from a classic GDI font definition,
/// like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls
/// on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public byte GdiCharSet => _gdiCharSet;
/// <summary>
/// Determines if this font was created to represent a GDI vertical font. This will only be valid if this font
/// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool GdiVerticalFont => _gdiVerticalFont;
/// <summary>
/// This property is required by the framework and not intended to be used directly.
/// </summary>
[Browsable(false)]
public string? OriginalFontName => _originalFontName;
/// <summary>
/// Gets the name of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public string SystemFontName => _systemFontName;
/// <summary>
/// Returns true if this <see cref='Font'/> is a SystemFont.
/// </summary>
[Browsable(false)]
public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName);
/// <summary>
/// Gets the height of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public int Height => (int)Math.Ceiling(GetHeight());
/// <summary>
/// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet.
/// </summary>
internal GpFont* NativeFont => _nativeFont;
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
~Font() => Dispose(false);
private Font(SerializationInfo info, StreamingContext context)
{
string name = info.GetString("Name")!; // Do not rename (binary serialization)
FontStyle style = (FontStyle)info.GetValue("Style", typeof(FontStyle))!; // Do not rename (binary serialization)
GraphicsUnit unit = (GraphicsUnit)info.GetValue("Unit", typeof(GraphicsUnit))!; // Do not rename (binary serialization)
float size = info.GetSingle("Size"); // Do not rename (binary serialization)
Initialize(name, size, style, unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, IsVerticalName(name));
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
string name = string.IsNullOrEmpty(OriginalFontName) ? Name : OriginalFontName;
si.AddValue("Name", name); // Do not rename (binary serialization)
si.AddValue("Size", Size); // Do not rename (binary serialization)
si.AddValue("Style", Style); // Do not rename (binary serialization)
si.AddValue("Unit", Unit); // Do not rename (binary serialization)
}
private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@';
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFont is not null)
{
try
{
#if DEBUG
Status status = !Gdip.Initialized ? Status.Ok :
#endif
PInvoke.GdipDeleteFont(_nativeFont);
#if DEBUG
Debug.Assert(status == Status.Ok, $"GDI+ returned an error status: {status}");
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFont = null;
}
}
}
/// <summary>
/// Returns the height of this Font in the specified graphics context.
/// </summary>
public float GetHeight(Graphics graphics)
{
ArgumentNullException.ThrowIfNull(graphics);
if (graphics.NativeGraphics is null)
{
throw new ArgumentException(nameof(graphics));
}
float height;
PInvoke.GdipGetFontHeight(NativeFont, graphics.Pointer(), &height).ThrowIfFailed();
GC.KeepAlive(this);
GC.KeepAlive(graphics);
return height;
}
public float GetHeight(float dpi)
{
float height;
PInvoke.GdipGetFontHeightGivenDPI(NativeFont, dpi, &height).ThrowIfFailed();
GC.KeepAlive(this);
return height;
}
/// <summary>
/// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this
/// <see cref='Font'/>.
/// </summary>
public override bool Equals([NotNullWhen(true)] object? obj)
{
if (obj == this)
{
return true;
}
if (obj is not Font font)
{
return false;
}
// Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties
// here.
// We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't
// have access to private/internal fields.
return font.FontFamily.Equals(FontFamily)
&& font.GdiVerticalFont == GdiVerticalFont
&& font.GdiCharSet == GdiCharSet
&& font.Style == Style
&& font.Size == Size
&& font.Unit == Unit;
}
/// <summary>
/// Gets the hash code for this <see cref='Font'/>.
/// </summary>
public override int GetHashCode()
{
return HashCode.Combine(Name, Style, Size, Unit);
}
/// <summary>
/// Returns a human-readable string representation of this <see cref='Font'/>.
/// </summary>
public override string ToString() =>
$"[{GetType().Name}: Name={FontFamily.Name}, Size={_fontSize}, Units={(int)_fontUnit}, GdiCharSet={_gdiCharSet}, GdiVerticalFont={_gdiVerticalFont}]";
// This is used by SystemFonts when constructing a system Font objects.
internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName;
public void ToLogFont(object logFont, Graphics graphics)
{
ArgumentNullException.ThrowIfNull(logFont);
Type type = logFont.GetType();
int nativeSize = sizeof(LOGFONT);
if (Marshal.SizeOf(type) != nativeSize)
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException(null, nameof(logFont));
}
ToLogFont(out LOGFONT nativeLogFont, graphics);
// PtrToStructure requires that the passed in object not be a value type.
if (!type.IsValueType)
{
Marshal.PtrToStructure(new IntPtr(&nativeLogFont), logFont);
}
else
{
GCHandle handle = GCHandle.Alloc(logFont, GCHandleType.Pinned);
Buffer.MemoryCopy(&nativeLogFont, (byte*)handle.AddrOfPinnedObject(), nativeSize, nativeSize);
handle.Free();
}
}
#if NET8_0_OR_GREATER
public
#else
private
#endif
void ToLogFont(out LOGFONT logFont, Graphics graphics)
{
ArgumentNullException.ThrowIfNull(graphics);
fixed (LOGFONT* lf = &logFont)
{
PInvoke.GdipGetLogFont(NativeFont, graphics.Pointer(), (LOGFONTW*)lf).ThrowIfFailed();
GC.KeepAlive(this);
GC.KeepAlive(graphics);
}
// Prefix the string with '@' if this is a gdiVerticalFont.
if (_gdiVerticalFont)
{
Span<char> faceName = logFont.lfFaceName;
faceName[..^1].CopyTo(faceName[1..]);
faceName[0] = '@';
// Docs require this to be null terminated
faceName[^1] = '\0';
}
if (logFont.lfCharSet == 0)
{
logFont.lfCharSet = _gdiCharSet;
}
}
/// <summary>
/// Creates the GDI+ native font object.
/// </summary>
private void CreateNativeFont()
{
Debug.Assert(_nativeFont is null, "nativeFont already initialized, this will generate a handle leak.");
Debug.Assert(_fontFamily is not null, "fontFamily not initialized.");
// Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so
// if creating the font object from an external FontFamily, this object's FontFamily will share the same native object.
GpFont* font;
Status status = PInvoke.GdipCreateFont(_fontFamily.Pointer(), _fontSize, (int)_fontStyle, (Unit)_fontUnit, &font);
GC.KeepAlive(this);
_nativeFont = font;
// Special case this common error message to give more information
if (status == Status.FontStyleNotFound)
{
throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString()));
}
else if (status != Status.Ok)
{
throw status.GetException();
}
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/>
/// and <see cref='FontStyle'/>.
/// </summary>
public Font(Font prototype, FontStyle newStyle)
{
// Copy over the originalFontName because it won't get initialized
_originalFontName = prototype.OriginalFontName;
Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(family, emSize, style, unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(family, emSize, style, unit, gdiCharSet, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
{
Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, FontStyle style)
{
Initialize(family, emSize, style, GraphicsUnit.Point, (byte)FONT_CHARSET.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize, GraphicsUnit unit)
{
Initialize(family, emSize, FontStyle.Regular, unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(FontFamily family, float emSize)
{
Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, (byte)FONT_CHARSET.DEFAULT_CHARSET, false);
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit)
{
Initialize(familyName, emSize, style, unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, FontStyle style)
{
Initialize(familyName, emSize, style, GraphicsUnit.Point, (byte)FONT_CHARSET.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize, GraphicsUnit unit)
{
Initialize(familyName, emSize, FontStyle.Regular, unit, (byte)FONT_CHARSET.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
public Font(string familyName, float emSize)
{
Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, (byte)FONT_CHARSET.DEFAULT_CHARSET, IsVerticalName(familyName));
}
/// <summary>
/// Constructor to initialize fields from an existing native GDI+ object reference. Used by ToLogFont.
/// </summary>
private Font(GpFont* nativeFont, byte gdiCharSet, bool gdiVerticalFont)
{
Debug.Assert(_nativeFont is null, "GDI+ native font already initialized, this will generate a handle leak");
Debug.Assert(nativeFont is not null, "nativeFont is null");
_nativeFont = nativeFont;
GraphicsUnit unit;
float size;
FontStyle style;
GpFontFamily* family;
PInvoke.GdipGetFontUnit(_nativeFont, (Unit*)&unit).ThrowIfFailed();
PInvoke.GdipGetFontSize(_nativeFont, &size).ThrowIfFailed();
PInvoke.GdipGetFontStyle(_nativeFont, (int*)&style).ThrowIfFailed();
PInvoke.GdipGetFamily(_nativeFont, &family).ThrowIfFailed();
SetFontFamily(new FontFamily(family));
Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
_originalFontName = familyName;
SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true));
Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
/// <summary>
/// Initializes this object's fields.
/// </summary>
private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
{
ArgumentNullException.ThrowIfNull(family);
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
Status status;
_fontSize = emSize;
_fontStyle = style;
_fontUnit = unit;
_gdiCharSet = gdiCharSet;
_gdiVerticalFont = gdiVerticalFont;
if (_fontFamily is null)
{
// GDI+ FontFamily is a singleton object.
SetFontFamily(new FontFamily(family.NativeFamily));
}
if (_nativeFont is null)
{
CreateNativeFont();
}
// Get actual size.
float size;
status = PInvoke.GdipGetFontSize(_nativeFont, &size);
_fontSize = size;
GC.KeepAlive(this);
Gdip.CheckStatus(status);
}
/// <summary>
/// Creates a <see cref='Font'/> from the specified Windows handle.
/// </summary>
public static Font FromHfont(IntPtr hfont)
{
PInvokeCore.GetObject((HGDIOBJ)hfont, out LOGFONT logFont);
using var hdc = GetDcScope.ScreenDC;
return FromLogFont(in logFont, hdc);
}
/// <summary>
/// Creates a <see cref="Font"/> from the given LOGFONT using the screen device context.
/// </summary>
/// <param name="lf">A boxed LOGFONT.</param>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static Font FromLogFont(object lf)
{
using var hdc = GetDcScope.ScreenDC;
return FromLogFont(lf, hdc);
}
#if NET8_0_OR_GREATER
public
#else
internal
#endif
static Font FromLogFont(in LOGFONT logFont)
{
using var hdc = GetDcScope.ScreenDC;
return FromLogFont(logFont, hdc);
}
#if NET8_0_OR_GREATER
public
#else
internal
#endif
static Font FromLogFont(in LOGFONT logFont, IntPtr hdc)
{
Status status;
GpFont* font;
fixed (LOGFONT* lf = &logFont)
{
status = PInvoke.GdipCreateFontFromLogfont((HDC)hdc, (LOGFONTW*)lf, &font);
}
// Special case this incredibly common error message to give more information
if (status == Status.NotTrueTypeFont)
{
throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Status.Ok)
{
throw Gdip.StatusException(status);
}
// GDI+ returns font = 0 even though the status is Ok.
if (font is null)
{
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, logFont.AsString()));
}
return new Font(font, logFont.lfCharSet, logFont.IsGdiVerticalFont);
}
/// <summary>
/// Creates a <see cref="Font"/> from the given LOGFONT using the given device context.
/// </summary>
/// <param name="lf">A boxed LOGFONT.</param>
/// <param name="hdc">Handle to a device context (HDC).</param>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static Font FromLogFont(object lf, IntPtr hdc)
{
ArgumentNullException.ThrowIfNull(lf);
if (lf is LOGFONT logFont)
{
// A boxed LOGFONT, just use it to create the font
return FromLogFont(in logFont, hdc);
}
Type type = lf.GetType();
int nativeSize = sizeof(LOGFONT);
if (Marshal.SizeOf(type) != nativeSize)
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException(null, nameof(lf));
}
// Now that we know the marshalled size is the same as LOGFONT, copy in the data
logFont = default;
Marshal.StructureToPtr(lf, new IntPtr(&logFont), fDeleteOld: false);
return FromLogFont(in logFont, hdc);
}
/// <summary>
/// Creates a <see cref="Font"/> from the specified handle to a device context (HDC).
/// </summary>
/// <returns>The newly created <see cref="Font"/>.</returns>
public static Font FromHdc(IntPtr hdc)
{
GpFont* font;
Status status = PInvoke.GdipCreateFontFromDC((HDC)hdc, &font);
// Special case this incredibly common error message to give more information
if (status == Status.NotTrueTypeFont)
{
throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Status.Ok)
{
throw Gdip.StatusException(status);
}
return new Font(font, 0, gdiVerticalFont: false);
}
/// <summary>
/// Creates an exact copy of this <see cref='Font'/>.
/// </summary>
public object Clone()
{
GpFont* font;
PInvoke.GdipCloneFont(_nativeFont, &font).ThrowIfFailed();
GC.KeepAlive(this);
return new Font(font, _gdiCharSet, _gdiVerticalFont);
}
private void SetFontFamily(FontFamily family)
{
_fontFamily = family;
// GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed
// objects with same family name share the underlying GDI+ native pointer. The unmanaged object is
// destroyed when its ref-count gets to zero.
//
// Make sure _fontFamily is not finalized so the underlying singleton object is kept alive.
GC.SuppressFinalize(_fontFamily);
}
[return: NotNullIfNotNull(nameof(familyName))]
private static string? StripVerticalName(string? familyName)
{
if (familyName?.Length > 1 && familyName[0] == '@')
{
return familyName[1..];
}
return familyName;
}
public void ToLogFont(object logFont)
{
using var hdc = GetDcScope.ScreenDC;
using Graphics graphics = Graphics.FromHdcInternal(hdc);
ToLogFont(logFont, graphics);
}
#if NET8_0_OR_GREATER
public void ToLogFont(out LOGFONT logFont)
{
using var hdc = GetDcScope.ScreenDC;
using Graphics graphics = Graphics.FromHdcInternal(hdc);
ToLogFont(out logFont, graphics);
}
#endif
/// <summary>
/// Returns a handle to this <see cref='Font'/>.
/// </summary>
public IntPtr ToHfont()
{
using var hdc = GetDcScope.ScreenDC;
using Graphics graphics = Graphics.FromHdcInternal(hdc);
ToLogFont(out LOGFONT lf, graphics);
HFONT handle = PInvokeCore.CreateFontIndirect((LOGFONTW*)&lf);
return handle.IsNull ? throw new Win32Exception() : handle;
}
public float GetHeight()
{
using var hdc = GetDcScope.ScreenDC;
using Graphics graphics = Graphics.FromHdcInternal(hdc);
return GetHeight(graphics);
}
/// <summary>
/// Gets the size, in points, of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public float SizeInPoints
{
get
{
if (Unit == GraphicsUnit.Point)
{
return Size;
}
using var hdc = GetDcScope.ScreenDC;
using Graphics graphics = Graphics.FromHdcInternal(hdc);
float pixelsPerPoint = (float)(graphics.DpiY / 72.0);
float lineSpacingInPixels = GetHeight(graphics);
float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style);
return emHeightInPixels / pixelsPerPoint;
}
}
}