[Delphi]怎樣訪問Internet Explorer中的WebBrowser

來源:互聯網
上載者:User

下面就是一個例子展示如何從開啟的Internet Explorer中取得其網頁元素的HTML原始碼:

const
  RSPSIMPLESERVICE = 1;
  RSPUNREGISTERSERVICE = 0;

type
  TObjectFromLResult = function(LRESULT: lResult; const IID: TIID; WPARAM: wParam; out pObject): HRESULT; stdcall;

function GetIEFromHWND(WHandle: HWND; var IE: IWebbrowser2): HRESULT;
var
  hInst: HWND;
  lRes: Cardinal;
  MSG: Integer;
  pDoc: IHTMLDocument2;
  ObjectFromLresult: TObjectFromLresult;
begin
  hInst := LoadLibrary('Oleacc.dll');
  @ObjectFromLresult := GetProcAddress(hInst, 'ObjectFromLresult');
  if @ObjectFromLresult <> nil then
  begin
    try
      MSG := RegisterWindowMessage('WM_HTML_GETOBJECT');
      SendMessageTimeOut(WHandle, MSG, 0, 0, SMTO_ABORTIFHUNG, 1000, lRes);
      Result := ObjectFromLresult(lRes, IHTMLDocument2, 0, pDoc);
      if Result = S_OK then
        (pDoc.parentWindow as IServiceprovider).QueryService(IWebbrowserApp, IWebbrowser2, IE);
    finally
      FreeLibrary(hInst);
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  All: IHtmlElementCollection;
  HtmlElement: IHtmlElement;
  I: Integer;
  Document: IHtmlDocument2;
  IE: IWebBrowser2;
  Wnd: HWND;
  WndChild: HWND;
begin
  Wnd := FindWindow('IEFrame', nil);
  if Wnd = 0 then
  begin
    MessageDlg('No Running instance of Internet Explorer!', mtError, [mbOK], 0);
  end;
  // walk Shell DocObject View->Internet Explorer_Server
  WndChild := FindWindowEX(Wnd, 0, 'Shell DocObject View', nil);
  if WndChild <> 0 then
  begin
    WndChild := FindWindowEX(WndChild, 0, 'Internet Explorer_Server', nil);
    if WndChild <> 0 then
    begin
      GetIEFromHWnd(WndChild, IE); //Get Iwebbrowser2 from Handle
      Document := IE.Document as IHtmlDocument2;
      if Assigned(Document) then
      begin
        All := Document.All;
        for I := 0 to All.Length - 1 do
        begin
          HtmlElement := All.item(i, 0) as IhtmlElement;
          SourceView.Lines.Add(IntToStr(i) + ' ' + HTmlElement.innerHTML);
        end;
      end;
    end;
  end;
end;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.