procedure TMainForm.Grab(bm: TBitMap);
var
hWnd: THandle;
pPid: DWORD;
hProcess: THandle;
n: Integer;
hdcSrc: THandle;
SourceRect: TRect;
//bmp: TBitmap;
//cBmp: HBITMAP;
TopLeft: TPoint;
begin
hWnd := GetForeGroundWindow;
if hWnd = 0 then Exit;
try
//RedrawWindow(hWnd, nil, 0, RDW_INVALIDATE or RDW_UPDATENOW);
//Application.ProcessMessages;
GetWindowThreadProcessID(hWnd, pPid);
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, pPid);
SetLength(ModuleFileName, 255);
n := GetProcessImageFileName(hProcess, PChar(ModuleFileName), 255);
//On Windows 2003 GetProcessImageFileName always returns 129?
n := Strlen(PChar(ModuleFileName));
SetLength(ModuleFileName, n);
SetLength(ClassName, 255);
n := GetClassName(hWnd, PChar(ClassName), 255);
SetLength(ClassName, n);
SetLength(WindowTitle, 255 );
n := SendMessage(hWnd, WM_GETTEXT, Length(WindowTitle), Integer(WindowTitle));
SetLength(WindowTitle, n);
{$IFDEF LOGFILE}
writeln(LogFile, 'ClassName=', ClassName);
writeln(LogFile, 'ModuleFileName=', ModuleFileName);
writeln(LogFile, 'WindowTitle=', WindowTitle);
{$ENDIF}
hdcSrc := GetDC(GetDesktopWindow);
if hdcSrc = 0 then
raise(CGException.Create('hdcSrc returned nil'));
Windows.GetClientRect(hWnd, SourceRect);
{$IFDEF LOGFILE}
writeln(LogFile, 'SourceRect Top/Left/Bottom/Right=', SourceRect.Top, ' ', SourceRect.Left, ' ',
SourceRect.Bottom, ' ', SourceRect.Right);
{$ENDIF}
bm.Width := SourceRect.Right - SourceRect.Left;
bm.Height := SourceRect.Bottom - SourceRect.Top;
TopLeft.X := SourceRect.Left;
TopLeft.Y := SourceRect.Top;
Windows.ClientToScreen(hWnd, TopLeft);
{$IFDEF LOGFILE}
writeln(LogFile, 'TopLeft X/Y=', TopLeft.X, ' ', TopLeft.Y);
{$ENDIF}
//bmp := Graphics.TBitmap.Create;
//cBmp := CreateCompatibleBitmap(hdcSrc, bm.Width, bm.Height);
//bmp.Handle := cBmp;
//BitBlt(bmp.Canvas.Handle, 0, 0, bm.Width, bm.Height, hdcSrc, SourceRect.Left, SourceRect.Top, SRCCOPY);
//bmp.Canvas.Changed;
//StretchBlt(bm.Canvas.Handle, 0, 0, bm.Width, bm.Height, hdcSrc,
//0, 0, SourceRect.Right - SourceRect.Left, SourceRect.Bottom - SourceRect.Top,
//SRCCOPY);
BitBlt(bm.Canvas.Handle, 0, 0, bm.Width, bm.Height, hdcSrc, TopLeft.X, TopLeft.Y, SRCCOPY);
//BitBlt(bm.Canvas.Handle, 0, 0, bm.Width, bm.Height, bmp.Canvas.Handle, SourceRect.Left, SourceRect.Top, SRCCOPY);
bm.Canvas.Changed;
finally
ReleaseDC(GetDesktopWindow, hdcSrc);
end;