1.当前窗体
public static Image CaptureControl(Control ctrl)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ctrl.Width, ctrl.Height);
ctrl.DrawToBitmap(bmp, new Rectangle(0, 0, ctrl.Width, ctrl.Height));
return bmp;
}
private void DownLoad()
{
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取应用程序运行的路径
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";//以日期命名文件名
try
{
var image = CaptureControl(this);
image.Save(filePath + fileName, ImageFormat.Png);
}
catch (Exception ex)
{
//异常处理
}
}
2.当前屏幕
private void saveB()
{
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取应用程序运行的路径
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";//以日期命名文件名
try
{
Screen screen = Screen.AllScreens.FirstOrDefault();//获取当前第一块屏幕(根据需求也可以换其他屏幕)
//创建需要截取的屏幕区域
Rectangle rc = new Rectangle(0, 0, 200, 200);
//生成截图的位图容器
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
//GDI+图像画布
using (Graphics memoryGrahics = Graphics.FromImage(bitmap))
{
memoryGrahics.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy);//对屏幕指定区域进行图像复制
}
bitmap.Save(filePath + fileName, ImageFormat.Png);
MessageBox.Show("文件保存在:" + filePath + fileName);
}
catch (Exception ex)
{
//异常处理
MessageBox.Show(ex.ToString());
}
}
3. 当前屏幕
private void CaptureScreen()
{
// 创建一个和屏幕一样大小的Bitmap
Rectangle bounds = Screen.PrimaryScreen.Bounds;
using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(bounds.Width, bounds.Height))
{
// 拷贝屏幕到Bitmap
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
// 保存Bitmap到文件
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "screenshot.png";
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}
}