WinSnap_delphi_snapshot_screen_capture

Print Friendly
WinSnap_delphi_snapshot_screen_capture

WinSnap_delphi_snapshot_screen_capture

Or, commonly called screen capture. In Delphi, in order not to degrade the quality of image capture/snapshot, TBitmap typed data usually used to hold the result. It can be converted later to other image formats as desired.

Starting from the Win32 API, each window in Windows has its own handle, an integer of type DWORD (4 bytes). Desktop also is a window. If we know the handle of a window, we can obtain its device context (DC) in the form of a  another handle of type HDC (Handle of Device Context). From the DC handle, we can copy the content of the DC to the Bitmap.

Delphi has made it easier to access and manage a DC using a class named TCanvas. On TCanvas we can draw, create text, create visual effects, or copy from and to another TCanvas object.The following code snippet to retrieve Desktop window handle, take the DC handle (HDC) and copied it onto a TBitmap object, and display it on a TImage on the form.

function TFMain.SnapDesktop: TBitmap;
var
DC: TCanvas;
HDesk: THandle;
HCanvas: HDC;
w, h: integer;
begin
HDesk := GetDesktopWindow;
RefreshDesktop;
DC:= TCanvas.Create;
Result := TBitmap.Create;
try
dc.Handle := GetWindowDC(hdesk);
w := Screen.Width;
h := Screen.Height;
Result.Width := w;
Result.Height := h;
BitBlt(Result.Canvas.Handle, 0,0,w, h, dc.Handle, 0, 0, SRCCOPY);
finally
DC.Free;
end;
end;

In the code above, we encountered several functions:

  • GetDesktopWindow () to retrieve the Windows desktop handle.
  • GetWindowDC (handleWindow) to retrieve the device context handle, in this case the Windows desktop.
  • BitBlt () to copy the content of a device context (DC) to another device context. In the above example, copying from desktop DC to Bitmap DC.

SnapDesktop function above returns an instance of the TBitmap which can then be displayed to the TImage, or saved as an image file, or converted to other image formats. In this example, the Bitmap image will be converted to JPG (TJPEGImage) with the following code:

jpg :=  TJPEGImage.Create;
try
jpg.Assign(VariabelBitmap);
jpg.SaveToFile(NamaFile);
finally
jpg.Free;
end;

In the example code available for download, also available afunction to crop the image so only certain parts are taken into the snapshot.

The following pictures are screenshots of the sample application:

Download

Downloa WinSnap:

WinSnap Binary – 730KB
WinSnap Binary (7Zipped) – 280KB
WinSnap Source (7Zipped) – 20KB

UPDATE:

WinSnap Binary + Source (7Zipped) – 300KB. Added new functionality, to snap selected window only.

 

Comments

comments

Powered by Facebook Comments