How do I capture a WinForm window to a bitmap without the caret

Posted by Steve Dunn on Stack Overflow See other posts from Stack Overflow or by Steve Dunn
Published on 2010-03-31T21:35:49Z Indexed on 2010/03/31 21:43 UTC
Read the original article Hit count: 346

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about winform

Related posts about win32