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

南笙酒味 提交于 2019-12-24 01:11:13

问题


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


来源:https://stackoverflow.com/questions/2556639/how-do-i-capture-a-winform-window-to-a-bitmap-without-the-caret

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!