DrawUtils.Win32.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Drawing;
  3. using System.Runtime.InteropServices;
  4. using System.Windows.Forms;
  5. namespace FastReport.Utils
  6. {
  7. partial class DrawUtils
  8. {
  9. [DllImport("user32.dll")]
  10. static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, DrawingOptions drawingOptions);
  11. const int WM_PRINT = 0x317;
  12. [Flags]
  13. enum DrawingOptions
  14. {
  15. PRF_CHECKVISIBLE = 0x01,
  16. PRF_NONCLIENT = 0x02,
  17. PRF_CLIENT = 0x04,
  18. PRF_ERASEBKGND = 0x08,
  19. PRF_CHILDREN = 0x10,
  20. PRF_OWNED = 0x20
  21. }
  22. private static void FloodFill(Bitmap bmp, int x, int y, Color color, Color replacementColor)
  23. {
  24. if (x < 0 || y < 0 || x >= bmp.Width || y >= bmp.Height || bmp.GetPixel(x, y) != color)
  25. return;
  26. bmp.SetPixel(x, y, replacementColor);
  27. FloodFill(bmp, x - 1, y, color, replacementColor);
  28. FloodFill(bmp, x + 1, y, color, replacementColor);
  29. FloodFill(bmp, x, y - 1, color, replacementColor);
  30. FloodFill(bmp, x, y + 1, color, replacementColor);
  31. }
  32. /// <summary>
  33. /// Draws control to a bitmap.
  34. /// </summary>
  35. /// <param name="control">Control to draw.</param>
  36. /// <param name="children">Determines whether to draw control's children or not.</param>
  37. /// <returns>The bitmap.</returns>
  38. public static Bitmap DrawToBitmap(Control control, bool children)
  39. {
  40. Bitmap bitmap = new Bitmap(control.Width, control.Height);
  41. using (Graphics gr = Graphics.FromImage(bitmap))
  42. {
  43. IntPtr hdc = gr.GetHdc();
  44. DrawingOptions options = DrawingOptions.PRF_ERASEBKGND | DrawingOptions.PRF_CLIENT | DrawingOptions.PRF_NONCLIENT;
  45. if (children)
  46. options |= DrawingOptions.PRF_CHILDREN;
  47. SendMessage(control.Handle, WM_PRINT, hdc, options);
  48. gr.ReleaseHdc(hdc);
  49. }
  50. if (control is Form)
  51. {
  52. // form has round edges which are filled black (DrawToBitmap issue/bug).
  53. FloodFill(bitmap, 0, 0, Color.FromArgb(0, 0, 0), Color.White);
  54. FloodFill(bitmap, bitmap.Width - 1, 0, Color.FromArgb(0, 0, 0), Color.White);
  55. }
  56. return bitmap;
  57. }
  58. }
  59. }