How do I capture a WinForm window to a bitmap with

2019-07-15 01:50发布

问题:

I've got window on a WinForm that I want to get the bitmap representation of. For this, I use the following code (where codeEditor is the control I want a bitmap representation of):

    public Bitmap GetBitmap( )
    {
        IntPtr srcDC = NativeMethods.GetDC( codeEditor.Handle ) ;
        var bitmap = new Bitmap( codeEditor.Width, codeEditor.Height ) ;

        Graphics graphics = Graphics.FromImage( bitmap ) ;

        var deviceContext = graphics.GetHdc( ) ;
        bool blitted = NativeMethods.BitBlt(
            deviceContext,
            0,
            0,
            bitmap.Width,
            bitmap.Height,
            srcDC,
            0,
            0,
            0x00CC0020 /*SRCCOPY*/ ) ;
        if ( !blitted )
        {
            throw new InvalidOperationException(
                @"The bitmap could not be generated." ) ;
        }

        int result = NativeMethods.ReleaseDC( codeEditor.Handle, srcDC ) ;
        if ( result == 0 )
        {
            throw new InvalidOperationException( @"Cannot release bitmap resources." ) ;
        }

        graphics.ReleaseHdc( deviceContext ) ;
        graphics.Dispose( ) ;

The trouble is, this captures the caret if it's flashing in the window at the time of capture. I tried calling the Win32 method HideCaret before capturing, but it didn't seem to have any effect.

回答1:

Well, one way is to set a focus to some other control of a form - and possibly restore the focus to a text field later on.



回答2:

What happens when you just do this?

public Bitmap GetBitmap()
{
    Bitmap bmp = new Bitmap(codeEditor.Width, codeEditor.Height);
    Rectangle rect = new Rectangle(0, 0, codeEditor.Width, codeEditor.Height);
    codeEditor.DrawToBitmap(bmp, rect);
    return bmp;
}