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.