您可以创建位图图像以在表单中呈现像素:
// Assuming this code is within the form code-behind,
// so this is instance of Form class.
using (var bmp = new System.Drawing.Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
bmp.Save("formScreenshot.bmp"); //or change another format.
}
为了保持干净,您可以创建扩展方法。例如:
public static class FormExtentions
{
public static System.Drawing.Bitmap TakeScreenshot(this Form form)
{
if (form == null)
throw new ArgumentNullException("form");
form.DrawToBitmap(bmp, new Rectangle(0, 0, form.Width, form.Height));
return bmp;
}
public static void SaveScreenshot(this Form form, string filename, System.Drawing.Imaging.ImageFormat format)
{
if (form == null)
throw new ArgumentNullException("form");
if (filename == null)
throw new ArgumentNullException("filename");
if (format == null)
throw new ArgumentNullException("format");
using (var bmp = form.TakeScreenshot())
{
bmp.Save(filename, format);
}
}
}
表单代码隐藏中的用法:
this.SaveScreenshot("formScreenshot.png",
System.Drawing.Imaging.ImageFormat.Png); //or other formats
注意: DrawToBitmap
将仅绘制屏幕上的内容。
编辑:虽然 OP 中的图像是png
您可以使用:bmp.Save("formScreenshot.png", System.Drawing.Imaging.ImageFormat.Png);