//声明一个API函数
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest, // 目标 DC的句柄
int nXDest,
int nYDest,
int nWidth,
int nHeight,
IntPtr hdcSrc, // 源DC的句柄
int nXSrc,
int nYSrc,
System.Int32 dwRop // 光栅的处理数值
);
/// <summary>
/// 保存控件的截图
/// </summary>
/// <param name="control">控件</param>
public static void Screenshots(Control control)
{
string dirPath = System.Windows.Forms.Application.StartupPath + @"\ScreenShots\";
string fileName = dirPath + DateTime.Now.ToString("ScreenyyyyMMddHHmmss") + ".png";
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
try
{
//获得控件的大小
Rectangle rect = new Rectangle(0, 0, control.Width - 19, control.Height - 4);
//Rectangle rect = new Rectangle(control.PointToScreen(new Point(0,0)), control.Size);
//创建一个以控件为模板的图象
Graphics g1 = control.CreateGraphics();
//创建以控件大小为标准的位图
Image MyImage = new Bitmap(rect.Width, rect.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
//得到控件的DC
IntPtr dc1 = g1.GetHdc();
//得到Bitmap的DC
IntPtr dc2 = g2.GetHdc();
//调用此API函数,实现屏幕捕获
BitBlt(dc2, 0, 0, rect.Width, rect.Height, dc1, 0, 0, 13369376);
//释放掉屏幕的DC
g1.ReleaseHdc(dc1);
//释放掉Bitmap的DC
g2.ReleaseHdc(dc2);
//以JPG文件格式来保存
MyImage.Save(fileName, ImageFormat.Png);
}
catch (Exception e)
{
MessageBox.Show("截图失败:" + e.Message, "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("截图成功!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}