主要内容是进行全屏抓图和窗口抓图
本例功能是每隔10秒对当前窗口(或一个固定的窗口)进行抓图,并保存到文件中。
…… 系统产生代码略
using System.Runtime.InteropServices;//add
namespace 截屏幕图
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
internal class NativeMethods
{
[DllImport("user32.dll")]
public extern static IntPtr GetDesktopWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern UInt64 BitBlt
(IntPtr hDestDC,
int x, int y, int nWidth, int nHeight,
IntPtr hSrcDC,
int xSrc, int ySrc, System.Int32 dwRop);
}
public class Form1 : System.Windows.Forms.Form
{
…… 系统产生代码略
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
//整个屏幕
public void SaveScreen(string filename)
{
Image myImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
Graphics gr1 = Graphics.FromImage(myImage);
IntPtr dc1 = gr1.GetHdc();
IntPtr dc2 = GetWindowDC(NativeMethods.GetDesktopWindow());
BitBlt(dc1, 0, 0, Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, dc2, 0, 0, 13369376);
gr1.ReleaseHdc(dc1);
myImage.Save(filename);
}
//当前窗口
public void SaveWindowsScreen(string filename)
{
Image newImage =new Bitmap(this.Width, this.Height);
Graphics newGraphics = Graphics.FromImage(newImage);
IntPtr ImageDc = newGraphics.GetHdc();
IntPtr SourceDc = GetWindowDC(this.Handle);
BitBlt(ImageDc, 0, 0, this.Width, this.Height, SourceDc, 0, 0, 13369376);
newGraphics.ReleaseHdc(ImageDc);
newImage.Save(filename);
}
private void Form1_Load(object sender, System.EventArgs e)
{
//this.WindowState =FormWindowState.Minimized ;
SaveScreen("screenshot.jpg");
}
private void timer1_Tick(object sender, System.EventArgs e)
{
label1.Text=DateTime.Now.ToString();
n=n+1;
SaveWindowsScreen("screenshot"+n.ToString()+".jpg");
}
}
}