如何从运行时创建的Web浏览器的客户端区域创建位图



在Windows 10 x64上的Delphi 10.4.2 Win32 VCL应用程序中,我需要从web浏览器的客户端区域创建一个特定大小的位图。web浏览器加载本地SVG。您可以在此处获取SVG:https://svgshare.com/s/Uzf

unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleCtrls, SHDocVw,
Vcl.StdCtrls, Vcl.ComCtrls;
type
TForm1 = class(TForm)
btnDoIt: TButton;
procedure btnDoItClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
CodeSiteLogging;
procedure PaintWebBrowserClientAreaToBitmap(AWB: TWebBrowser; AOut: Vcl.Graphics.TBitmap);
var
DC: Winapi.Windows.HDC;
begin
if not Assigned(AOut) then
Exit;
if not Assigned(AWB) then
Exit;
DC := GetWindowDC(AWB.Handle);
AOut.Width := AWB.Width;
AOut.Height := AWB.Height;
with AOut do
Winapi.Windows.BitBlt(Canvas.Handle, 0, 0, Width, Height, DC, 0, 0, Winapi.Windows.SrcCopy);
ReleaseDC(AWB.Handle, DC);
end;
procedure TForm1.btnDoItClick(Sender: TObject);
var
B: TBitmap;
begin
B := TBitmap.Create;
try
var wb2: SHDocVw.TWebBrowser;
wb2 := SHDocVw.TWebBrowser.Create(nil);
try
//wb2.Name := 'wb2';
wb2.SelectedEngine := IEOnly;
wb2.ClientWidth := 300;
wb2.ClientHeight := 525;
wb2.Navigate('file:///C:DELPHI_testBrowserSVGViewersteamreactor.svg');
PaintWebBrowserClientAreaToBitmap(wb2, B);
CodeSite.Send('B', B);
ShowMessage('test'); // halt here to see the nice image
finally
wb2.Free;
end;
finally
B.Free;
end;
end;
end.

这将在屏幕上创建一个非常短的可见图像。但是位图仍然是空的!

我怎样才能做到这一点?(屏幕上可能没有出现任何图像(。

您必须等待WebBrowser完成工作:

procedure TForm1.btnDoItClick(Sender: TObject);
var
B   : TBitmap;
wb2 : SHDocVw.TWebBrowser;
begin
B := TBitmap.Create;
try
wb2 := SHDocVw.TWebBrowser.Create(nil);
try
wb2.SelectedEngine := IEOnly;
wb2.ClientWidth    := 300;
wb2.ClientHeight   := 525;
wb2.Navigate('file:///E:TEMPsteamreactor.svg');
repeat
Application.ProcessMessages;
until not wb2.Busy;
PaintWebBrowserClientAreaToBitmapOld(wb2, B);
Image1.Picture.Bitmap := B;
finally
wb2.Free;
end;
finally
B.Free;
end;
end;

调用Application.ProcessMessages不是等待浏览器终止的最佳方式。但这是另一个故事:-(

为了方便查看图像,我在表单上添加了TImage。当然,你可以对位图为所欲为。

如果您需要的是用SVG制作位图,那么有Delphi库可以做到这一点。谷歌是你的朋友:-(

最新更新