Delphi图象截取编程示例(2)

类别:Delphi 点击:0 评论:0 推荐:

(四)创建抓取图象的单元文件ScrnCpt

unit ScrnCpt;

interface

uses windows,forms,controls,classes,Graphics;
function CaptureScreenRect(ARect:TRect):TBitmap;
function CaptureScreen:TBitmap;
function CaptureClientImage(Control:TControl):TBitmap;
function CaptureControlImage(Control:TControl):TBitmap;
function CaptureWindowImage(Wnd:HWND):TBitmap;

implementation

function CaptureScreenRect(ARect:TRect):TBitmap;
var ScreenDC:HDC;    //设备描述表的句柄
begin
  result:=TBitmap.Create ;
  with Result,ARect do
  begin
    Width :=Right-left;
    Height:=Bottom-Top;
    ScreenDC:=GetDC(0); //获取一个窗口的设备描述表的句柄,0参数返回屏幕窗口设备描述表的句柄
    try
      //BOOL BitBlt(hdcDest,nXDest,nYDest,nWidth,nHeight,hdcSrc,nXSrc,nYSrc,dwRop)
      //把位图从源设备描述表hdcSrc复制到目标设备描述表hdcDest,
      //光栅操作码dwRop指定了 源图的组合方式
      BitBlt(Canvas.Handle ,0,0,Width,Height,ScreenDC,left,top,SRCCOPY);
    finally
      ReleaseDC(0,ScreenDC);
    end;
  end;
end;

//全屏抓图
function CaptureScreen:TBitmap;
begin
  with Screen do
    result:=CaptureScreenRect(Rect(0,0,width,height));
end;

//抓取一个窗体或控件的客户区图象
function CaptureClientImage(Control:TControl):TBitmap;
begin
  //Control.ClientOrigin是控件客户区的左上角位置。x,y是 ClientOrigin的变量
  with Control,Control.ClientOrigin do
    result:=CaptureScreenRect(Bounds(x,y,ClientWidth,ClientHeight));
end;

// 抓取一整个窗体或控件
function CaptureControlImage(Control:TControl):TBitmap;
begin
  with Control do
    if Parent=nil then //无父窗体,根据它的位置,直接抓取
      result:=CaptureScreenRect(Bounds(left,top,width,height))
    else  //有父窗体,把它转化为相对于屏幕坐标,再 抓取
      with Parent.ClientToScreen(Point(Left,top))do
        result:=CaptureScreenRect(Bounds(x,y,width,height));
end;

//根据窗体句柄进行抓取
function CaptureWindowImage(Wnd:HWND):TBitmap;
var R:TRect;
begin
  GetWindowRect(wnd,R); //把窗口句柄指定的窗口坐标放入TRect
  result:=CaptureScreenRect(R);
end;

end.

本文地址:http://com.8s8s.com/it/it4711.htm