今天無聊翻代碼,翻出來一個以前寫的C#截屏的函數...拿出來和大家共享一下.這段代碼是參照網上一段截屏的C++代碼改寫的.只不過把API都聲明了一下而已.聲明的各API也附後.以供參照.如有問題歡迎指出.([email protected])
///
/// 截取部分屏幕
///
/// 左上角
/// 右下角
/// 是否全屏幕
/// 返回值Bitmap
public 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, GetDeviceCapsIndex.HORZRES);//獲取屏幕寬度
yscrn = GetDeviceCaps(hscrdc, GetDeviceCapsIndex.VERTRES);//獲取屏幕高度
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
}