我们可以使用navigate方法来使TWebbrowser显示指定的内容,也可以使用下面的方法来设置TWebbrowser的显示内容:
var
Doc: IHTMLDocument2;
begin
Doc := WebBrowser.Document as IHTMLDocument2;
if Assigned(Doc) and Assigned(Doc.body) then
Doc.body.innerHTML:=Content;
然而在使用中发现,TWebbrowser只有在窗体显示后才会激活,如果在一个已显示的窗口中这样来设置TWebbrowser的内容是没有问题的,但如果在窗口显示前,比如说在窗口的Create事件中这样来设置,则会出现一个“该文档内容已改变,保存修改吗”的对话框。
那么如果我们要在窗口显示后直接显示内容怎么办?
经测试,可以使用线程来解决这个问题:
创建一个简单的线程类:
TShowHTML = class(TThread)
private
{ Private declarations }
aWeb:TWebBrowser;
protected
procedure Execute; override;
procedure SetContent;
published
property Web:TWebBrowser read aWeb write aWeb;
end;
然后实现:
procedure TShowHTML.Execute;
begin
{ Place thread code here }
Synchronize(SetContent);//异步执行,主要是为了访问窗口的可视控件的线程安全
end;
procedure TShowHTML.SetContent;
begin
while aWeb.ReadyState <>READYSTATE_COMPLETE do
begin
Sleep(10);
Application.ProcessMessages;
end;
//showmessage('OK');
SetHtml(aWeb,s);
end;
在窗体的Create事件中就可以这样来调用了:
with TShowHTML.Create(True) do
begin
Web:=wb1;
FreeOnTerminate:=True;
Resume;
end;
不知道有没有在窗口显示前就能激活TWebbrowser的方法。即在Form的Create事件中可以设置TWebbrowser的内容,而不出现那个讨厌的对话框。
在网上找了好多关闭那个对话框的方法,都不理想。