如何在Delphi 10中截取Active Window的截图?

时间:2017-09-07 13:47:23

标签: delphi screenshot

许多年前,How to take a screenshot of the Active Window in Delphi?就提出了这个问题。我复制了完全相同的代码,但我无法使截图工作。我一直得到的是黑色32x20pixel,3KB Jpeg文件。我的完整代码如下,我做错了什么?

unit Unit1;

interface

 uses
   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
 TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
 { Public declarations }
         end;

var
 Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
const FullWindow = true;
var
Win : HWND;
DC: HDC;
Bmp: TBitmap;
 FileName: string;
 WinRect: TRect ;
 Width: Integer;
 Height: Integer;
begin


Form1.Hide;
try
  Application.ProcessMessages;
  Win := GetForegroundWindow;
  if FullWindow then
  begin
    Winapi.Windows.GetWindowRect(Win, WinRect);
DC := GetWindowDC(Win);
  end else
  begin
    Winapi.Windows.GetClientRect(Win, WinRect);
    DC := GetDC(Win);
  end;
  try

Width := WinRect.Right - WinRect.Left;
Height := WinRect.Bottom - WinRect.Top;
Bmp := TBitmap.Create;
try
  Bmp.Height := Height;
  Bmp.Width := Width;
  BitBlt(Bmp.Canvas.Handle, 0, 0, Width, Height, DC, 0, 0, SRCCOPY);
  FileName := 'Screenshot_'+
    FormatDateTime('mm-dd-yyy-hhnnss', Now());
  Bmp.SaveToFile(Format('C:\Screenshot\%s.bmp', [FileName]));
finally
  Bmp.Free;
end;
  finally
    ReleaseDC(Win, DC);
  end;
finally
  Form1.Show;
end;
end;

end.

0 个答案:

没有答案