文档详情

delphi中Webbrowser使用技巧.doc

发布:2017-07-09约4.9万字共26页下载文档
文本预览下载声明
WebBrowser组件和MSHTML 在Delphi中的使用 由于项目需要,近来研究了一下WebBrowser组件和MSHTML 在Delphi中的使用,整理了一下这段时间研究的结果,写下来一是方便大家查阅,二也可以加深我自己的记忆.希望能对大家有所帮助… …,同时,如果有更好的处理方式或者我没有提到的问题,请大家也告诉我哦, 咱们一块进步… ...,其中一部分是我从网络中搜集的资料,谢谢那些兄弟们… … MSHTML把HTML页面中的元素封装成了IHTMLInputElement、 IHTMLInputButtonElement、IHTMLInputTextElement、IHTMLTextAreaElement、IHTMLTitleElement、IHTMLFormElement等等组件接口。 在程序中可以通过MSHTML提供的IHTMLDocument2接口得到整个Document对象,IHTMLElementCollection接口得到所有页面元素的集合,通过该接口的Item方法可以得到具体的某个组件,然后设置和读取该组件的属性值。 下面是一些常用功能的事例代码. 1. 打开某个页面: web.Navigate(ExtractFilePath(Application.ExeName) + Template/login.html); 2. 取出页面中某个HtmlElement的Value属性值: function GetValueByElementName(web: TWebBrowser; elementName: string; index: integer): string; begin result := (((web.Document as IHTMLDocument2).body.all as IHTMLElementCollection).item(elementName, index) as IHTMLInputElement ).value end; 3. 给HtmlElement设置Value属性 procedure SetValueTextAreaName(web: TWebBrowser; elementName, value: string;index: integer); begin (((web.Document as IHTMLDocument2).body.all as IHTMLElementCollection).item(elementName, index) as IHTMLTextAreaElement ).value := value; end; 4. 判断页面执行结果是否成功 因为Web应用中如果出错的一般是采用错误页面的方式呈现给最终用户,所以我们也无法抓到Http错误,只能通过在webBeforeNavigate2事件中将URL参数记录到全局变量中, 然后在webDocumentComplete事件中根据URL参数和全局变量中的URL参数来判断执行结果是否正确.当然,这样需要将页面地址编码到代码中,降低了灵活性,但是这也是我能想到的唯一的方法,如果大家有什么好的方法,请告诉我哦. 5. 屏蔽鼠标右键和某些快捷键 本功能需要在webBrowser的窗口中加入ApplicationEvents组件,设置它的OnMessage事件代码如下即可. procedure TwebAdapterForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); const _KeyPressMask = begin //禁用右键 with Msg do begin if not IsChild(web.Handle, hWnd) then Exit; Handled := (message = WM_RBUTTONDOWN) or (message = WM_RBUTTONUP) or (message = WM_CONTEXTMENU); end; //禁止Ctrl + N //禁止Ctrl + F //禁止Ctrl + A if Msg.message = WM_KEYDOWN then begin if ((Msg.lParam and _KeyPressMask) = 0) and (GetKeyState(VK_Control) 0) and ((Msg.wParam = Ord(N)) or (Msg.wParam = Ord(F)) or (Msg.wParam = Ord(A))) then begin Handled := True; end; end; end;
显示全部
相似文档