1. Computing

How to Capture the Screen Shot of the Active Window

How to Capture the Screen Shot of the Active Window

From , former 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

©2013 About.com. All rights reserved.