Getting a screenshot of the screen or form or form
   


A common question I've come across is how to get a screenshot in Delphi. ScreenShot() will take a shot of a box onscreen and place it in a TBitmap for you. To get the whole screen, use it like this: ScreenShot(0, 0, Screen.Width, Screen.Height, Image1.Picture.Bitmap); For just a shot of a form, do this: ScreenShot(Form1.Left, Form1.Top, Form1.Width, Form1.Height, Image1.Picture.Bitmap); Thanks to Joe C. Hecht for this code.

procedure ScreenShot(x : integer;
                    y : integer; //(x, y) = Left-top coordinate
                    Width : integer;
                    Height : integer; //(Width-Height) = Bottom-Right coordinate
                    bm : TBitMap); //Destination
var
  dc: HDC;
  lpPal: PLOGPALETTE;
begin
  {test width and height}
  if ((Width = 0) or (Height = 0)) then
    Exit;

  bm.Width := Width;
  bm.Height := Height;
  {get the screen dc}
  dc := GetDc(0);
  if (dc = 0) then
    Exit;

  {do we have a palette device?}
  if (GetDeviceCaps(dc, RASTERCAPS) and RC_PALETTE = RC_PALETTE) then
    begin
      {allocate memory for a logical palette}
      GetMem(lpPal, SizeOf(TLOGPALETTE) + (255 * SizeOf(TPALETTEENTRY)));
      {zero it out to be neat}
      FillChar(lpPal^, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)), #0);
      {fill in the palette version}
      lpPal^.palVersion := $300;
      {grab the system palette entries}
      lpPal^.palNumEntries := GetSystemPaletteEntries(dc, 0, 256, lpPal^.palPalEntry);
      if (lpPal^.PalNumEntries <> 0) then
        {create the palette}
        bm.Palette := CreatePalette(lpPal^);
      FreeMem(lpPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)));
    end;

  {copy from the screen to the bitmap}
  BitBlt(bm.Canvas.Handle, 0, 0, Width, Height, Dc, x, y, SRCCOPY);
  {release the screen dc}
  ReleaseDc(0, dc);
end;


Blue Orb Software

[email protected]