Déclaration des constantes Win32 :
public const int WM_PRINT = 0x0317;
public const int PRF_NONCLIENT = 0x00000002;
public const int PRF_CLIENT = 0x00000004;
public const int PRF_ERASEBKGND = 0x00000008;
public const int PRF_CHILDREN = 0x00000010;
public const int PRF_OWNED = 0x00000020;
...
Et le corps de la méthode
Bitmap bmp = new Bitmap(this.Width, this.Height);
Graphics bmpGraphics = Graphics.FromImage(bmp);
IntPtr bmpHdc = bmpGraphics.GetHdc();
Message msg = new Message();
msg.Msg = WM_PRINT;
msg.HWnd = this.Handle;
msg.WParam = bmpHdc;
msg.LParam = new IntPtr(PRF_NONCLIENT |
PRF_CLIENT |
PRF_ERASEBKGND|
PRF_CHILDREN|
PRF_OWNED);
this.WndProc(ref msg);
bmpGraphics.ReleaseHdc(bmpHdc);
bmpGraphics.Dispose();
Si vous souhaitez capturer un controle particulier, il faut modifier ces lignes :
Bitmap bmp = new Bitmap(this.Width, this.Height);
msg.HWnd = this.Handle;
En remplacant this par le nom du Control voulu.
Vous pouvez ensuite utiliser la variable bmp comme bon vous semble
Dans ce Post, coq a donné une solution equivalente, mais en la mettant en forme dans une méthode toute faite, alors autant vous en faire profiter:
private
const int WM_PRINT = 0x0317;
private const int PRF_CHECKVISIBLE = 0x00000001;
private const int PRF_NONCLIENT = 0x00000002;
private const int PRF_CLIENT = 0x00000004;
private const int PRF_ERASEBKGND = 0x00000008;
private const int PRF_CHILDREN = 0x00000010;
private const int PRF_OWNED = 0x00000020;public Bitmap PrintWindowEx()
{
Bitmap bmp = null;
Graphics gr = null;
IntPtr hdc = IntPtr.Zero;
try
{
bmp = new Bitmap( this.ClientRectangle.Width, this.ClientRectangle.Height, this.CreateGraphics() );
gr = Graphics.FromImage(bmp);
hdc = gr.GetHdc();
IntPtr wParam = hdc;
IntPtr lParam = new IntPtr(PRF_CLIENT | PRF_CHILDREN);
Message msg = Message.Create(this.Handle, WM_PRINT, wParam, lParam);
this.WndProc(ref msg);
}
catch{}
finally
{
if ( gr != null )
{
if (hdc != IntPtr.Zero)
gr.ReleaseHdc(hdc);
gr.Dispose();
}
}
return bmp;
}