1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Capture the Screen Shot of the Active Window
How to Capture the Screen Shot of the Active Window

By , About.com Guide

Screen Shot Active Window

Need to take a screen shoot from code? No problem ... here's how to capture the Windows desktop or the Active Window's image into a TBitmap object - and display it inside a TImage control.

Drop a TImage on a Form and use the following code:

procedure ScreenShot(activeWindow: bool; destBitmap : TBitmap) ;
var
   w,h : integer;
   DC : HDC;
   hWin : Cardinal;
   r : TRect;
begin
   if activeWindow then
   begin
     hWin := GetForegroundWindow;
     dc := GetWindowDC(hWin) ;
     GetWindowRect(hWin,r) ;
     w := r.Right - r.Left;
     h := r.Bottom - r.Top;
   end
   else
   begin
     hWin := GetDesktopWindow;
     dc := GetDC(hWin) ;
     w := GetDeviceCaps (DC, HORZRES) ;
     h := GetDeviceCaps (DC, VERTRES) ;
   end;

   try
    destBitmap.Width := w;
    destBitmap.Height := h;
    BitBlt(destBitmap.Canvas.Handle,
           0,
           0,
           destBitmap.Width,
           destBitmap.Height,
           DC,
           0,
           0,
           SRCCOPY) ;
   finally
    ReleaseDC(hWin, DC) ;
   end;
end;
Usage:
var
   b:TBitmap;
begin
  b := TBitmap.Create;
  try
    ScreenShot(TRUE, b) ;
    Image1.Picture.Bitmap.Assign(b) ;
  finally
    b.FreeImage;
    FreeAndNil(b) ;
  end;
Note: the first parameter in the TakeShot is a bool value indicating whether to take a screen shot of the active window or to grab what's currently on the desktop window.

For an example application, download the source code.

Delphi tips navigator:
» How to "Pan" an Image inside a ScrollBox
« Remove the Windows Constraint on Minimum Form Size: Width and Height

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Capture the Screen Shot of the Active Window from Delphi Code

©2009 About.com, a part of The New York Times Company.

All rights reserved.