Delphi下TWebBrowser控件的使用

    技术2025-01-13  11

    程序需要访问网页时,delphi一般可以两种方式实现。一种是通过Tidhttp,这种方式post数据需要通过网页抓包等方式,模拟网页的post提交。

    第二种是通过Twebbrowser控件访问,这种方式比较简单,现在将近期一个程序的关键部分记录下来,以备各位朋友参考。

    一、访问网页

    WebBrowser1.Navigate('http://www.baidu.com');

    二、防止弹出的对话框或页面关闭webrowser控件

    procedure TMyForm.WebBrowser1WindowClosing(ASender: TObject; IsChildWindow: WordBool; var Cancel: WordBool); begin Cancel := true; end;

    三、得到frameset中frame内容为src 网址的document,因为如果用webbrowser1.documnent.frames取不到他的document

    procedure TMyForm.WebBrowser1DocumentComplete(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant); begin if RightPosEx('input.php',URL) > 0 then//判断URL是需要的地址 begin myDocument := (pDisp as IWebBrowser2).Document as IHTMLDocument2; end end;

    四、得到IHTMLDocument2如何操作

    procedure TMyForm.btLogoutClick(Sender: TObject); var myForm:IHTMLFormElement; begin if Assigned(myDocument) then begin if RightPosEx('判断页面标题',myDocument.title) <= 0 then begin Memo1.Lines.Add('你没有成功登陆!'); Exit; end; myForm := myDocument.forms.item('portal',0) as IHTMLFormElement; myForm.action :='do_logout.php'; myDocument.parentWindow.execScript('IsSubmitLogout = 1','JavaScript'); (myForm.item('logouttype',0) as IHTMLInputElement).value := 'TYPESUBMIT'; myForm.submit; end; end;

    五、禁止页面弹出对话框(主要是csdn论坛中一位大侠的方法)

    uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw, StdCtrls,mshtml, ExtCtrls, ComCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,IdHTTP, IdAntiFreezeBase, IdAntiFreeze,IniFiles,ActiveX; const WM_DOWNSTART = WM_USER +1000; type IDocHostShowUI = interface(IUnknown) ['{c4d244b0-d43e-11cf-893b-00aa00bdce1a}'] function ShowMessage(hwnd: THandle; lpstrText: POLESTR; lpstrCaption: POLESTR;dwType: longint; lpstrHelpfile: POLESTR; dwHelpContext: longint;var plResult: LRESULT): HRESULT; stdcall; function ShowHelp(hwnd: THandle; pszHelpfile: POLESTR; uCommand: integer;dwData: longint; ptMouse: TPoint; var pDispatchObjectHit: IDispatch): HRESULT; stdcall; end; TWebBrowser = class(SHDocVw.TWebBrowser,IDocHostShowUI) protected function ShowMessage(hwnd: THandle; lpstrText: POLESTR; lpstrCaption: POLESTR;dwType: longint; lpstrHelpfile: POLESTR; dwHelpContext: longint;var plResult: LRESULT): HRESULT; stdcall; function ShowHelp(hwnd: THandle; pszHelpfile: POLESTR; uCommand: integer;dwData: longint; ptMouse: TPoint; var pDispatchObjectHit: IDispatch): HRESULT; stdcall; end; function TWebBrowser.ShowHelp(hwnd: THandle; pszHelpfile: POLESTR; uCommand, dwData: Integer; ptMouse: TPoint; var pDispatchObjectHit: IDispatch): HRESULT; begin Result := S_FALSE; end; function TWebBrowser.ShowMessage(hwnd: THandle; lpstrText, lpstrCaption: POLESTR; dwType: Integer; lpstrHelpfile: POLESTR; dwHelpContext: Integer; var plResult: LRESULT): HRESULT; begin // plResult := MessageBoxW(hwnd,PWChar(lpstrText),'不得闲测试',65); Result := S_OK; end;

    有什么需要共同研究的就留言吧。

    最新回复(0)