Archive

Archive for August, 2009

Screen/Desktop grab in Delphi

August 2nd, 2009

Ever wanted to grab all the desktop/screen in Delphi? Right, me too. I spent a lot of time searching around for different options, as usual, google is your friend. Lots of info available on the web but this code snippet works well:

{------------------------------------------------------------------------------}

procedure TfmMain.Grab(bm: TBitMap; gt : GrabType);
var
 DestRect, SourceRect: TRect;
 h: THandle;
 hdcSrc : THandle;
 pt : TPoint;
begin
hdcSrc := 0 ;
 case(gt) of
 GTWINDOW, GTCLIENT : h := GetForeGroundWindow;
 GTSCREEN : h := GetDesktopWindow;
 else h := 0;
 end;
 if h <> 0 then
 begin
 try
 if gt = GTCLIENT then
 begin
 hdcSrc := GetDC(h); // use this for ClientRect
 Windows.GetClientRect(h,SourceRect);
 end
 else
 begin
 hdcSrc := GetWindowDC(h);
 GetWindowRect(h, SourceRect);
 end;
 bm.Width  := SourceRect.Right - SourceRect.Left;
 bm.Height := SourceRect.Bottom - SourceRect.Top;
 DestRect := Rect(0, 0, SourceRect.Right - SourceRect.Left, SourceRect.Bottom - SourceRect.Top);
 StretchBlt(bm.Canvas.Handle, 0, 0, bm.Width,
 bm.Height, hdcSrc,
 0,0,SourceRect.Right - SourceRect.Left,
 SourceRect.Bottom - SourceRect.Top,
 SRCCOPY);
 if gt = GTCLIENT then
 begin
 pt.X :=SourceRect.Left;
 pt.Y :=SourceRect.Top;
 // call Windows.ClientToScreen() to translate X and Y
 Windows.ClientToScreen(h, pt);
 // DrawCursor(bm,pt.X, pt.Y);
 end
 //
 else
 begin
 // DrawCursor(bm,SourceRect.Left, SourceRect.Top);
 end;
 finally
 ReleaseDC(0, hdcSrc);
 end;
 end;
end;

Code snippet, Delphi