How To Capture Screen with Delphi

This short article will explain you how to capture screen content to a JPEG file from the Delphi program.

Step 1

First create a new project. (I assume you already have experience with Delphi programming so I will not go into detail on how to create a Delphi project.)  Save it, for example, as ScrnCap. Rename main form as frmCapture. Add a TButton control and a TSaveDialog. Rename button control as btnStartCapture and change its Caption properties to 'Capture'. Rename save dialog as dlgSaveCapture.

 

Step 2

Create a new unit and rename is as uscreencap.pas. Add the following code:

procedure CaptureScreenShot(acapture: TBitMap);
var c: TCanvas;
r: TRect;
begin
   c:= TCanvas.Create;
   c.Handle:= GetWindowDC (GetDesktopWindow);
   try
     r:= Rect(0,0,screen.width,screen.height);
     acapture.Width:=screen.Width;
     acapture.Height:=screen.Height;
     acapture.Canvas.CopyRect(r, c, r);
 finally
     ReleaseDC(0, c.handle);
     c.Free;
 end;
end;

procedure CaptureScreenShotJPEG(ajpeg:TJPEGImage);
var abmp:TBitmap;
begin
  abmp:=TBitmap.Create;
  try
    CaptureScreenShot(abmp);
    ajpeg.Assign(abmp);
  finally
    abmp.Free;
  end;
end;

 

Do not forget to add jpeg.pas unit in uses clause of unit interface part. This is where TJPEGImage class is declared. Save it when you are finished.

Step 3

Now in your main application unit where the main form resides, add button OnClick event handler. Fill the code in exactly as it is below:

procedure TfrmCapture.btnStartCaptureClick(Sender:TObject);
var ajpeg:TJPEGImage;
begin
  ajpeg:=TJPEGImage.Create;
  try
    CaptureScreenShotJPEG(ajpeg);
    if dlgSaveCapture.Execute the
    begin
      ajpeg.SaveToFile(dlgSaveCapture.Filename);
    end;
  finally
   ajpeg.Free;
  end;
end;

 

Do not forget to include uscreencap.pas and jpeg.pas unit in your uses clause. Build project and run. Every time you clickcapture button, your screen is saved to JPEG file.

 

Share this article!

Follow us!

Find more helpful articles: