gpt4 book ai didi

delphi - 如何在Delphi中截取事件窗口的屏幕截图?

转载 作者:行者123 更新时间:2023-12-03 14:39:12 24 4
gpt4 key购买 nike

对于完整的屏幕截图,我使用以下代码:

form1.Hide;
sleep(500);
bmp := TBitmap.Create;
bmp.Height := Screen.Height;
bmp.Width := Screen.Width;
DCDesk := GetWindowDC(GetDesktopWindow);
BitBlt(bmp.Canvas.Handle, 0, 0, Screen.Width, Screen.Height, DCDesk, 0, 0, SRCCOPY);
form1.Show ;
FileName := 'Screenshot_'+FormatDateTime('mm-dd-yyyy-hhnnss',now());
bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
ReleaseDC(GetDesktopWindow, DCDesk);
bmp.Free;

如何将其转换为仅截取事件窗口的屏幕截图。

最佳答案

  1. 首先,您必须获得正确的窗口。正如 Sharptooth 已经指出的那样,您应该使用 GetForegroundWindow 而不是 GetDesktopWindow。你已经在你的improved version中做对了。 .
  2. 但是您必须将位图的大小调整为 DC/Window 的实际大小。您还没有完成此操作。
  3. 然后确保您没有捕获一些全屏窗口!

当我执行你的代码时,我的 Delphi IDE 被捕获,并且由于默认情况下它是全屏的,因此它创建了全屏屏幕截图的错觉。 (即使您的代码大部分是正确的)

考虑到上述步骤,我成功地使用您的代码创建了单窗口屏幕截图。

提示:如果您只对客户区感兴趣,可以使用 GetDC 而不是 GetWindowDC。 (无窗口边框)

编辑:这是我用您的代码所做的:

您不应该使用此代码!请看下面的改进版本。

procedure TForm1.Button1Click(Sender: TObject);
const
FullWindow = True; // Set to false if you only want the client area.
var
hWin: HWND;
dc: HDC;
bmp: TBitmap;
FileName: string;
r: TRect;
w: Integer;
h: Integer;
begin
form1.Hide;
sleep(500);
hWin := GetForegroundWindow;

if FullWindow then
begin
GetWindowRect(hWin,r);
dc := GetWindowDC(hWin) ;
end else
begin
Windows.GetClientRect(hWin, r);
dc := GetDC(hWin) ;
end;

w := r.Right - r.Left;
h := r.Bottom - r.Top;

bmp := TBitmap.Create;
bmp.Height := h;
bmp.Width := w;
BitBlt(bmp.Canvas.Handle, 0, 0, w, h, DC, 0, 0, SRCCOPY);
form1.Show ;
FileName := 'Screenshot_'+FormatDateTime('mm-dd-yyyy-hhnnss',now());
bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
ReleaseDC(hwin, DC);
bmp.Free;
end;

编辑 2: 根据要求,我添加了更好版本的代码,但我保留旧版本作为引用。您应该认真考虑使用它而不是原始代码。如果出现错误,它会表现得更好。 (资源已清理,您的表单将再次可见,...)

procedure TForm1.Button1Click(Sender: TObject);
const
FullWindow = True; // Set to false if you only want the client area.
var
Win: HWND;
DC: HDC;
Bmp: TBitmap;
FileName: string;
WinRect: TRect;
Width: Integer;
Height: Integer;
begin
Form1.Hide;
try
Application.ProcessMessages; // Was Sleep(500);
Win := GetForegroundWindow;

if FullWindow then
begin
GetWindowRect(Win, WinRect);
DC := GetWindowDC(Win);
end else
begin
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-yyyy-hhnnss', Now());
Bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
finally
Bmp.Free;
end;
finally
ReleaseDC(Win, DC);
end;
finally
Form1.Show;
end;
end;

关于delphi - 如何在Delphi中截取事件窗口的屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/661250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com