How to get a Windows Forms panel as a bitmap with

2019-07-20 04:55发布

问题:

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