NullGraphics.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Drawing;
  3. namespace PaintDotNet.SystemLayer
  4. {
  5. /// <summary>
  6. /// Sometimes you need a Graphics instance when you don't really have access to one.
  7. /// Example situations include retrieving the bounds or scanlines of a Region.
  8. /// So use this to create a 'null' Graphics instance that effectively eats all
  9. /// rendering calls.
  10. /// </summary>
  11. public sealed class NullGraphics
  12. : IDisposable
  13. {
  14. private IntPtr hdc = IntPtr.Zero;
  15. private Graphics graphics = null;
  16. private bool disposed = false;
  17. public Graphics Graphics
  18. {
  19. get
  20. {
  21. return graphics;
  22. }
  23. }
  24. public NullGraphics()
  25. {
  26. this.hdc = SafeNativeMethods.CreateCompatibleDC(IntPtr.Zero);
  27. if (this.hdc == IntPtr.Zero)
  28. {
  29. NativeMethods.ThrowOnWin32Error("CreateCompatibleDC returned NULL");
  30. }
  31. this.graphics = Graphics.FromHdc(this.hdc);
  32. }
  33. ~NullGraphics()
  34. {
  35. Dispose(false);
  36. }
  37. public void Dispose()
  38. {
  39. Dispose(true);
  40. GC.SuppressFinalize(this);
  41. }
  42. private void Dispose(bool disposing)
  43. {
  44. if (!disposed)
  45. {
  46. if (disposing)
  47. {
  48. this.graphics.Dispose();
  49. this.graphics = null;
  50. }
  51. SafeNativeMethods.DeleteDC(this.hdc);
  52. disposed = true;
  53. }
  54. }
  55. }
  56. }