如何等待TWebBrowser加载到FOR ... TO ... DO?

时间:2012-08-09 18:06:47

标签: delphi

我有一个代码:

    for i:=0 to Memo1.Lines.Count-1 do
       begin
           while WebBrowser1.Busy do Application.ProcessMessages;
           WebBrowser1.OleObject.Document.Links.item(cat[i]).click;
           subcatList;
       end;

但是,尽管程序有了预期,但WebBrowser1仍然运行了几次。如何在后台启动WebBrowser1或解决方案是什么?

1 个答案:

答案 0 :(得分:2)

您需要实现TWebBrowser,BeforeNavigate2,DocumentComplete和NavigateComplete2的3个事件

    TForm1 = class(TForm)
    private
      CurDispatch: IDispatch; 
      FDocLoaded: Boolean;    
    ....


    procedure TForm1.WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
      const URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
      var Cancel: WordBool);
    begin
      CurDispatch := nil;
      FDocLoaded := False;
    end;

    procedure TForm1.WebBrowser1DocumentComplete(ASender: TObject; const pDisp: IDispatch;
      const URL: OleVariant);
    begin
      if (pDisp = CurDispatch) then  
      begin
        FDocLoaded := True;
        CurDispatch := nil;
      end;
    end;

    procedure TForm1.WebBrowser1NavigateComplete2(ASender: TObject; const pDisp: IDispatch;
      const URL: OleVariant);
    begin
      if CurDispatch = nil then
        CurDispatch := pDisp;
    end;

现在您可以使用FDocLoaded变量来了解页面是否已加载到WebBrowser中

    WebBrowser1.Navigate('www.stackoverflow.com');
    repeat Application.ProcessMessage until FDocLoaded;

此致