Desktop / Window Screenshot via BitBlt - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

uses
  System.SysUtils, Winapi.Windows, VCL.Graphics, VCL.Imaging.pngimage;

// ...

function DesktopScreenshot(ATargetWindow : THandle = 0) : TBitmap;
begin
  result := nil;
  ///

  if ATargetWindow = 0 then
    ATargetWindow := GetDesktopWindow();

  var ARect : TRect;
  GetWindowRect(ATargetWindow, ARect);

  if ARect.IsEmpty then
    raise Exception.Create('Can''t capture a zero-bound window!');

  result := TBitmap.Create();

  result.Width := ARect.Width;
  result.Height := ARect.Height;

  var AWindowDC := GetWindowDC(ATargetWindow);
  try
    BitBlt(
      result.Canvas.Handle,
      0,
      0,
      result.Width,
      result.Height,
      AWindowDC,
      0,
      0,
      SRCCOPY
    );
  finally
    ReleaseDC(ATargetWindow, AWindowDC);
  end;
end;

// ...

// Important to capture correct window bound on HDPI monitors.
SetProcessDPIAware();
///

var ABitmap := DesktopScreenshot();
if Assigned(ABitmap) then begin
  var APng := TPngImage.Create();
  try
    APng.Assign(ABitmap);

    ///
    APng.SaveToFile('screenshot.png');
  finally
    FreeAndNil(APng);
    FreeAndNil(ABitmap);
  end;
end;

Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.

Implemented By Technique

Featured Windows API


Created

April 23, 2025

Last Revised

April 23, 2025