[c#] Capturer une représentation graphique d'un control

Introduction

Voici un simple bout de code permettant de récupérer dans un objet Bitmap la représentation graphique d'une Form ou de tout autre Control

1ère méthode

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 Control particulier, il faut modifier ces lignes :

Bitmap bmp = new Bitmap(this.Width, this.Height);
msg.HWnd = this.Handle;

En remplaçant this par le nom du Control voulu.
Vous pouvez ensuite utiliser la variable bmp comme bon vous semble

2e méthode

Dans ce Post, coq a donné une solution équivalente, 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;
}
Ce document intitulé « [c#] Capturer une représentation graphique d'un control » issu de CodeS SourceS (codes-sources.commentcamarche.net) est mis à disposition sous les termes de la licence Creative Commons. Vous pouvez copier, modifier des copies de cette page, dans les conditions fixées par la licence, tant que cette note apparaît clairement.
Rejoignez-nous