views:

87

answers:

2

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.

+3  A: 

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.

EFraim
+2  A: 

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;
}
MusiGenesis
Good assumption - I should have pointed out that the window contains third party components and one of them doesn't provide the correct image when using DrawToBitmap
Steve Dunn
@Steve: that's weird - I would have assumed that DrawToBitmap was just wrapping what you were doing anyway, and would thus produce the same image. Here's a lame idea: if the caret is always in the same place (probably isn't) can you just erase it from the bitmap (i.e. draw the backcolor over top of the caret)?
MusiGenesis
@MusiGenesis: depending on the font, the caret can overlap the text.
EFraim