32

您如何以编程方式获取 .Net 控件的图片?

4

7 回答 7

49

每个控件都有一个名为DrawToBitmap的方法。您不需要 p/invoke 来执行此操作。

Control c = new TextBox();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);
c.DrawToBitmap(bmp, c.ClientRectangle);
于 2008-11-05T18:27:34.777 回答
7

您可以使用从 .NET 2.0 开始的 Control 类的DrawToBitmap方法以编程方式轻松获取 .NET 控件的图片

这是VB中的示例

    Dim formImage As New Bitmap("C:\File.bmp")
    Me.DrawToBitmap(formImage, Me.Bounds)

这是在 C# 中:

 Bitmap formImage = New Bitmap("C:\File.bmp")
 this.DrawToBitmap(formImage, this.Bounds)
于 2008-11-05T18:29:54.070 回答
5

Control.DrawToBitmap将让您将大多数控件绘制到位图。这不适用于 RichTextBox 和其他一些。

如果要捕获这些或具有其中之一的控件,则需要像此 CodeProject 文章中所述执行 PInvoke:图像捕获

请注意,其中一些方法将捕获屏幕上的任何内容,因此如果您有另一个窗口覆盖您的控件,您将得到它。

于 2008-11-05T18:39:58.403 回答
3

对于支持它的 WinForms 控件,System.Windows.Forms.Control 类中有一个方法:

public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds);

但是,这不适用于所有控件。第三方组件供应商有更全面的解决方案。

于 2008-11-05T18:28:09.907 回答
3

这是对整个客户端进行操作的方法Form,而不仅仅是客户端区域(没有标题栏和其他修饰)

        Rectangle r = this.Bounds;
        r.Offset(-r.X,-r.Y);
        Bitmap bitmap = new Bitmap(r.Width,r.Height);
        this.DrawToBitmap(bitmap, r);
        Clipboard.SetImage(bitmap);
于 2013-05-06T23:25:39.720 回答
1

如果它不在您要执行的控件上,您通常可以将其转换为基本 Control 类并在那里调用 DrawToBitmap 方法。

于 2008-11-05T18:36:28.940 回答
1
Panel1.Dock = DockStyle.None ' If Panel Dockstyle is in Fill mode
Panel1.Width = 5000  ' Original Size without scrollbar
Panel1.Height = 5000 ' Original Size without scrollbar

Dim bmp As New Bitmap(Me.Panel1.Width, Me.Panel1.Height)
Me.Panel1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Panel1.Width, Me.Panel1.Height))
'Me.Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)
bmp.Save("C:\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

Panel1.Dock = DockStyle.Fill

注意:它工作正常

于 2011-06-09T13:37:44.690 回答