How to Capture Full Screen or Active Window Screenshot with Delphi

This short procedure will capture a screenshot with Delphi of the active window or the whole screen which you can manipulate or save.

By Tim TrottLegacy Code • February 6, 2004
How to Capture Full Screen or Active Window Screenshot with Delphi

Simply call this method with an instance of a TBitmap and the type of capture to grab. This can either be GTWINDOW or GTCLIENT. GTWINDOW will grab the current foreground window, or GTSCREEN to capture the entire screen in the screenshot with Delphi.

pascal
procedure GrabScreen(bm: TBitMap; gt : GrabType);
var
  DestRect, SourceRect: TRect;
  h: THandle;
  hdcSrc : THandle;
  pt : TPoint;
begin
  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
          //DrawCursor(bm,SourceRect.Left, SourceRect.Top);
    finally
      ReleaseDC(0, hdcSrc);
    end;
  end;
end;

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.