本文整理自网络,侵删。
今天一直在找一种快速稳定的WebBrowser直接读取html字符的方法,找到好多种,经过测试,下边这种方法比较好用,代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls, ExtCtrls,ActiveX;
type
TForm1 = class(TForm)
pnl1: TPanel;
btn1: TButton;
pnl2: TPanel;
wb1: TWebBrowser;
pnl3: TPanel;
mmo1: TMemo;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure LoadStream(WebBrowser:TWebBrowser; Stream:TStream);
var
PersistStreamInit: IPersistStreamInit;
StreamAdapter: IStream;
MemoryStream: TMemoryStream;
begin
WebBrowser.Navigate('about:blank');
repeat
Application.ProcessMessages;
Sleep(0);
until
WebBrowser.ReadyState=READYSTATE_COMPLETE;
if WebBrowser.Document.QueryInterface(IPersistStreamInit,PersistStreamInit)=S_OK then
begin
if PersistStreamInit.InitNew=S_OK then
begin
MemoryStream:=TMemoryStream.Create;
try
MemoryStream.CopyFrom(Stream,0);
MemoryStream.Position:=0;
except
MemoryStream.Free;
raise;
end;
StreamAdapter:=TStreamAdapter.Create(MemoryStream,soOwned);
PersistStreamInit.Load(StreamAdapter);
end;
end;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
S: TStringStream;
begin
S:= TStringStream.Create(mmo1.Text);
try
LoadStream(wb1,S);
finally
S.Free;
end;
End;
Initialization
OleInitialize(nil);
finalization
try
OleUninitialize;
except
end;
end.
====================================
object Form1: TForm1
Left = 220
Top = 64
Width = 696
Height = 563
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object pnl1: TPanel
Left = 0
Top = 507
Width = 688
Height = 29
Align = alBottom
TabOrder = 2
object btn1: TButton
Left = 320
Top = 2
Width = 75
Height = 25
Caption = '加载页面'
TabOrder = 0
OnClick = btn1Click
end
end
object pnl2: TPanel
Left = 0
Top = 0
Width = 688
Height = 360
Align = alClient
BevelOuter = bvNone
BorderStyle = bsSingle
Caption = 'pnl2'
TabOrder = 0
object wb1: TWebBrowser
Left = 0
Top = 0
Width = 684
Height = 356
Align = alClient
TabOrder = 0
ControlData = {
4C000000B2460000CB2400000000000000000000000000000000000000000000
000000004C000000000000000000000001000000E0D057007335CF11AE690800
2B2E126208000000000000004C0000000114020000000000C000000000000046
8000000000000000000000000000000000000000000000000000000000000000
00000000000000000100000000000000000000000000000000000000}
end
end
object pnl3: TPanel
Left = 0
Top = 360
Width = 688
Height = 147
Align = alBottom
Caption = 'pnl3'
TabOrder = 1
object mmo1: TMemo
Left = 1
Top = 1
Width = 686
Height = 145
Align = alClient
Lines.Strings = (
'在这里输入测试html代码')
TabOrder = 0
end
end
end
相关阅读 >>
Delphi 将 4 个 byte 合成 1 个 integer 的五种方法 - 回复 "三足乌" 的问题
更多相关阅读请进入《Delphi》频道 >>