C# 抓取屏幕图片
利用非托管库"GDI32.DLL"中的BitBlt方法来进行屏幕抓图
1:首要要引入的命名空间为:
using System.Drawing;
uisng System.Runtime.InteropServices;
2:导入非托管方法BitBlt:
private static extern bool BitBlt(IntPtr hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,int nXSrc,int nYSrc,Int32 dwrop);
3:定义抓图的方法:
private voidgetTheScreenPhoto()
{
Rectangle rScreen = new Rectangle();
rScreen =Screen.GetWorkingArea(this);//得到屏幕的区域
Grapgics gScreen = this.CreateGraphics();//为屏幕创建Grapgics;
Image iGetPhoto = new Bitmap(rScreen.Width,rScreen.Height,gScreen);//以屏幕的大小新建一个图片
Graphics gPhoto =Graphics.FromImage(iGetPhoto);//为图片创建一个Graphics用于画图
IntPtr iHandle = gScreen.GetHdc();//得到gScreen 的句柄
IntPtr iPhoto = gPhoto.GetHdc();//得到gPhoto的句柄
try
{
//调用BitBlt进行抓图
BitBlt(iPhoto,2,0,rScreen.Width,rScreen.Height,iHandle,0,0,13369376);
}
catch
{
return;
}
gScreen .ReleaseHdc(iHandle );//释放由gScreen.GetHdc()产生的句柄
gPhoto .ReleaseHdc(iPhoto );//释放由gPhoto.GetHdc()产生的句柄
//保存图片到本地
iGetPhoto.Save(保存的路径,格式);
}
1:首要要引入的命名空间为:
using System.Drawing;
uisng System.Runtime.InteropServices;
2:导入非托管方法BitBlt:
private static extern bool BitBlt(IntPtr hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,int nXSrc,int nYSrc,Int32 dwrop);
3:定义抓图的方法:
private voidgetTheScreenPhoto()
{
Rectangle rScreen = new Rectangle();
rScreen =Screen.GetWorkingArea(this);//得到屏幕的区域
Grapgics gScreen = this.CreateGraphics();//为屏幕创建Grapgics;
Image iGetPhoto = new Bitmap(rScreen.Width,rScreen.Height,gScreen);//以屏幕的大小新建一个图片
Graphics gPhoto =Graphics.FromImage(iGetPhoto);//为图片创建一个Graphics用于画图
IntPtr iHandle = gScreen.GetHdc();//得到gScreen 的句柄
IntPtr iPhoto = gPhoto.GetHdc();//得到gPhoto的句柄
try
{
//调用BitBlt进行抓图
BitBlt(iPhoto,2,0,rScreen.Width,rScreen.Height,iHandle,0,0,13369376);
}
catch
{
return;
}
gScreen .ReleaseHdc(iHandle );//释放由gScreen.GetHdc()产生的句柄
gPhoto .ReleaseHdc(iPhoto );//释放由gPhoto.GetHdc()产生的句柄
//保存图片到本地
iGetPhoto.Save(保存的路径,格式);
}