private static void FillRectanglesImpl(Graphics g, Color color, Rectangle[] rects) { uint nativeColor = (uint)(color.R + (color.G << 8) + (color.B << 16)); IntPtr hdc = IntPtr.Zero; IntPtr brush = IntPtr.Zero; IntPtr oldObject = IntPtr.Zero; try { hdc = g.GetHdc(); brush = SafeNativeMethods.CreateSolidBrush(nativeColor); if (brush == IntPtr.Zero) { NativeMethods.ThrowOnWin32Error("CreateSolidBrush returned NULL"); } oldObject = SafeNativeMethods.SelectObject(hdc, brush); foreach (Rectangle rect in rects) { NativeStructs.RECT nativeRect; nativeRect.left = rect.Left; nativeRect.top = rect.Top; nativeRect.right = rect.Right; nativeRect.bottom = rect.Bottom; int result = SafeNativeMethods.FillRect(hdc, ref nativeRect, brush); if (result == 0) { NativeMethods.ThrowOnWin32Error("FillRect returned zero"); } } } finally { if (oldObject != IntPtr.Zero) { SafeNativeMethods.SelectObject(hdc, oldObject); oldObject = IntPtr.Zero; } if (brush != IntPtr.Zero) { SafeNativeMethods.DeleteObject(brush); brush = IntPtr.Zero; } if (hdc != IntPtr.Zero) { g.ReleaseHdc(hdc); hdc = IntPtr.Zero; } } GC.KeepAlive(g); }