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.