How to get a Windows Forms panel as a bitmap with C#?

人走茶凉 提交于 2019-12-11 01:20:07

问题


I have a Windows form with a panel with several controls on it. The panel does not take up all of the form space, but only a small part. What I want to know is if there is some way to retrieve the display of the panel (with all child controls) as a bitmap. Like a screenshot but only cropped to the panel.

I am not looking into the screen capture because the panel is within the scrollable control (DevX controls) so at times it may not be fully visible and I need its visual representation whether visible or not.

Is this possible at all?

Edit:

Well, now it seems that it was as I feared. The suggested solution with DrawToBitmap() only draws the part of the control that is VISIBLE. I have used DisplayRectangle to retreive the size of the complete control. The rectangle is ok, and now the bitmap is the size of the complete control, but the part of the control that is NOT VISIBLE is TRANSPARENT on the bitmap, not displaying the controls that are on the invisible part of the control.

Is there any chance for this to be rendered completely?


回答1:


Sure, just use the panel's DrawToBitmap() method. It isn't 100% reliable, there might be controls on the panel that don't support it. Like RichTextBox, WebBrowser or some kind of 3rd party ActiveX control.

    private static Image PanelToBitmap(Control pnl) {
        var bmp = new Bitmap(pnl.Width, pnl.Height);
        pnl.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
        return bmp;
    }


来源:https://stackoverflow.com/questions/3181886/how-to-get-a-windows-forms-panel-as-a-bitmap-with-c

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