Delphi通過IE視窗控制程式碼獲取網頁介面(IWebBrowser2)

一劍平江湖發表於2013-12-10

主要用到的是MSAA(Microsoft Active Accessibility) 函式:ObjectFromLResult,該函式在動態連結庫 oleacc.dll 中定義。

uses SHDocVw, MsHtml, ActiveX;

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
  
Result := S_False;
  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;

呼叫例子,以下程式碼快速關閉所有開啟的IE視窗:

procedure TForm1.Button1Click(Sender: TObject);
var
    hCurWindow, hMainWnd, hTabWnd, hCldWnd:HWnd; //視窗控制程式碼
    WinClsName:array[0..255] of char;
    IE1: IWebbrowser2;
begin
    hCurWindow := GetWindow(Handle,GW_HWNDFirst);  //獲取第一個視窗的控制程式碼
    while hCurWindow<>0 do
    begin
       GetClassName(hCurWindow, @WinClsName, 255);
       if String(WinClsName) = 'IEFrame' then
       begin
         hMainWnd := hCurWindow;
         hCldWnd := hCurWindow;
         hTabWnd := 0;
         repeat //迴圈查詢所有選項卡
           hTabWnd := FindWindowEx(hMainWnd, hTabWnd, 'Frame Tab', nil);
           if hTabWnd <> 0 then hCldWnd := FindWindowEx(hTabWnd, 0, 'TabWindowClass', nil);
           if hCldWnd <> 0 then hCldWnd := FindWindowEx(hCldWnd, 0, 'Shell DocObject View', nil);
           if hCldWnd <> 0 then hCldWnd := FindWindowEx(hCldWnd, 0, 'Internet Explorer_Server', nil);
           if hCldWnd <> 0 then if GetIEFromHWnd(hCldWnd, IE1) = S_OK then //獲取IWebBrowser2
           begin
             IE1.Quit; //關閉IE,也可以執行其他操作,呵呵
           end;
         until hTabWnd = 0;
       end;
       hCurWindow:=GetWindow(hCurWindow,GW_HWNDNEXT); //獲取下一個視窗的控制程式碼
    end;
end; 

相關文章