2004-12-25

Painting a Control onto a Graphics object

Here's a little class in C#, that allows you to paint an existing Control onto a Graphics object. Nothing special, but useful if you need it. If you're using .NET 2.0, you don't need this class: see Control.DrawToBitmap.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class ControlPainter
{
  private const int
    WM_PRINT = 0x317, PRF_CLIENT = 4,
    PRF_CHILDREN = 0x10, PRF_NON_CLIENT = 2,
    COMBINED_PRINTFLAGS = PRF_CLIENT | PRF_CHILDREN | PRF_NON_CLIENT;

  [DllImport("USER32.DLL")]
  private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam);

  public static void PaintControl(Graphics graphics, Control control)
  { // paint control onto graphics
    IntPtr hWnd = control.Handle;
    IntPtr hDC = graphics.GetHdc();
    SendMessage(hWnd, WM_PRINT, hDC, COMBINED_PRINTFLAGS);
    graphics.ReleaseHdc(hDC);
  }
}
Using it is very easy: if you need to paint the Control myControl onto Graphics myGraphics, you just call ControlPainter.PaintControl(myGraphics, myControl)
Edited March 5th 2005: used some more flags, to also paint child controls and non-client elements like borders and titlebars. Thanks to Kent Boogaart. In this post on his blog, you can find a more flexible version of this method, where you can specify the flags yourself.
Edited October 29th 2005: as of .NET 2.0, the Control class has a method to draw itself to a Bitmap: DrawToBitmap. Thanks to an anonymous commenter for this tip.