Winforms 如何在没有插入符号的情况下将WinForm窗口捕获为位图

Winforms 如何在没有插入符号的情况下将WinForm窗口捕获为位图,winforms,graphics,winapi,gdi+,gdi,Winforms,Graphics,Winapi,Gdi+,Gdi,我在WinForm上有一个窗口,我想得到它的位图表示。 为此,我使用以下代码,其中codeEditor是我想要位图表示的控件: public Bitmap GetBitmap( ) { IntPtr srcDC = NativeMethods.GetDC( codeEditor.Handle ) ; var bitmap = new Bitmap( codeEditor.Width, codeEditor.Height ) ; G

我在WinForm上有一个窗口,我想得到它的位图表示。 为此,我使用以下代码,其中codeEditor是我想要位图表示的控件:

    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( ) ;

问题是,如果在捕获时插入符号在窗口中闪烁,则会捕获该插入符号。在捕获之前,我尝试调用Win32方法HideCaret,但似乎没有任何效果。

好的,一种方法是将焦点设置到表单的其他控件,并可能在稍后将焦点恢复到文本字段。

如果只执行此操作,会发生什么

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;
}

您可能需要一个C标记。很好的假设-我应该指出窗口包含第三方组件,其中一个在使用时没有提供正确的图像DrawToBitmap@Steve:这很奇怪-我本以为DrawToBitmap只是包装了你正在做的事情,因此会产生相同的图像。这里有一个蹩脚的想法:如果插入符号总是在同一个位置,可能不是。你可以从位图中删除它,即在插入符号的顶部绘制背景色吗?根据字体,插入符号可以与文本重叠。