SolidBrush
Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths. This class cannot be inherited.
using System.Drawing.Internal;
using System.Runtime.CompilerServices;
using Windows.Win32;
using Windows.Win32.Graphics.Gdi;
using Windows.Win32.Graphics.GdiPlus;
namespace System.Drawing
{
public sealed class SolidBrush : Brush, ISystemColorTracker
{
private Color _color = Color.Empty;
private bool _immutable;
public unsafe Color Color {
get {
if (_color == Color.Empty) {
ARGB argb = default(ARGB);
PInvoke.GdipGetSolidFillColor((GpSolidFill*)base.NativeBrush, (uint*)(&argb)).ThrowIfFailed();
GC.KeepAlive(this);
_color = argb;
}
return _color;
}
set {
if (_immutable)
throw new ArgumentException(System.SR.Format(System.SR.CantChangeImmutableObjects, "Brush"));
if (_color != value) {
Color color = _color;
InternalSetColor(value);
if (value.IsSystemColor && !color.IsSystemColor)
SystemColorTracker.Add(this);
}
}
}
public unsafe SolidBrush(Color color)
{
_color = color;
GpSolidFill* nativeBrushInternal = default(GpSolidFill*);
PInvoke.GdipCreateSolidFill((ARGB)ref _color, &nativeBrushInternal).ThrowIfFailed();
SetNativeBrushInternal((GpBrush*)nativeBrushInternal);
if (_color.IsSystemColor)
SystemColorTracker.Add(this);
}
internal SolidBrush(Color color, bool immutable)
: this(color)
{
_immutable = immutable;
}
internal unsafe SolidBrush(GpSolidFill* nativeBrush)
{
SetNativeBrushInternal((GpBrush*)nativeBrush);
}
[NullableContext(1)]
public unsafe override object Clone()
{
GpBrush* nativeBrush = default(GpBrush*);
PInvoke.GdipCloneBrush(base.NativeBrush, &nativeBrush).ThrowIfFailed();
GC.KeepAlive(this);
return new SolidBrush((GpSolidFill*)nativeBrush);
}
protected override void Dispose(bool disposing)
{
if (!disposing)
_immutable = false;
else if (_immutable) {
throw new ArgumentException(System.SR.Format(System.SR.CantChangeImmutableObjects, "Brush"));
}
base.Dispose(disposing);
}
private unsafe void InternalSetColor(Color value)
{
PInvoke.GdipSetSolidFillColor((GpSolidFill*)base.NativeBrush, (ARGB)ref value).ThrowIfFailed();
GC.KeepAlive(this);
_color = value;
}
unsafe void ISystemColorTracker.OnSystemColorChanged()
{
if (base.NativeBrush != null)
InternalSetColor(_color);
}
}
}