屏幕截取 |
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; using System.Collections; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices;
namespace ymz { /// <summary> /// 屏幕截取工具 /// 调用WinGDI-API实现屏幕截取 /// </summary> public class GetScreenTool {
/// 截取全屏
public static Bitmap GetScreen() { return GetPartScreen(Point.Empty, Point.Empty, true); } /// 截取屏幕特定区域 public static Bitmap GetScreen(Point p1, Point p2) { return GetPartScreen(p1, p2, false); }
#region 实现
/// 截取部分屏幕
private static Bitmap GetPartScreen(Point P1,Point P2, bool Full) { IntPtr hscrdc,hmemdc; IntPtr hbitmap,holdbitmap; int nx,ny,nx2,ny2; nx=ny=nx2=ny2=0; int nwidth, nheight; int xscrn, yscrn; hscrdc = CreateDC("DISPLAY", null, null, 0);//创建DC句柄 hmemdc = CreateCompatibleDC(hscrdc);//创建一个内存DC xscrn = GetDeviceCaps(hscrdc, 8/*HORZRES*/);//获取屏幕宽度//wingdi.h yscrn = GetDeviceCaps(hscrdc, 10/*VERTRES*/);//获取屏幕高度//wingdi.h if(Full)//如果是截取整个屏幕 { nx = 0; ny = 0; nx2 = xscrn; ny2 = yscrn; } else { nx = P1.X; ny = P1.Y; nx2 =P2.X; ny2 =P2.Y; //检查数值合法性 if(nx<0)nx = 0; if(ny<0)ny = 0; if(nx2>xscrn)nx2 = xscrn; if(ny2>yscrn)ny2 = yscrn; } nwidth = nx2 - nx;//截取范围的宽度 nheight = ny2 - ny;//截取范围的高度 hbitmap = CreateCompatibleBitmap(hscrdc, nwidth, nheight);//从内存DC复制到hbitmap句柄 holdbitmap = SelectObject(hmemdc, hbitmap); BitBlt(hmemdc, 0, 0, nwidth, nheight,hscrdc, nx, ny,(UInt32)0xcc0020); hbitmap = SelectObject(hmemdc, holdbitmap); DeleteDC(hscrdc);//删除用过的对象 DeleteDC(hmemdc);//删除用过的对象 return Bitmap.FromHbitmap(hbitmap);//用Bitmap.FromHbitmap从hbitmap返回Bitmap }
#region 所用到的API声明 [DllImport("gdi32.dll")] private static extern IntPtr CreateDC( string lpszDriver, string lpszDevice, string lpszOutput, Int64 lpInitData );
[DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC( IntPtr hdc );
[DllImport("gdi32.dll")] private static extern int GetDeviceCaps( IntPtr hdc, Int32 nIndex );
[DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap( IntPtr hdc, int nWidth, int nHeight );
[DllImport("gdi32.dll")] private static extern IntPtr SelectObject( IntPtr hdc, IntPtr hgdiobj );
[DllImport("gdi32.dll")] private static extern int BitBlt( IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, UInt32 dwRop );
[DllImport("gdi32.dll")] private static extern int DeleteDC( IntPtr hdc ); #endregion
#endregion |
评论