WebBrowser控件捕捉DHTML事件

王朝html/css/js·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

WebBrowser控件捕捉DHTML事件

作者:Tuenhai.com MSN: king#tuenhai.com

版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明

http://www.Tuenhai.com/

开发工具:Microsoft Visual Studio .NET 2003

操作系统:Windows XP

原文:http://www.devx.com/vb2themax/tip/18798

和其他控件一样,我们可以用WebBrowser控件来构筑Windows form应用程序。从工具箱中选择Windows 窗体控件组,单击“Microsoft Web 浏览器”,Visual Studio .NET 在后台使用AxImp.exe工具创建ActiveX 控件,控件名字为“AxWebBrowser”。在VB.NET中,不能直接使用COM组件,COM都是Unmanaged Code,在VB.NET中使用这些组件,必须完成从Unmanaged Code到Managed Code的转换。

一般地,你可以像使用原来的WebBrowser控件一样,如call 方法,指定属性,捕捉事件等。

有些事情并不是那么简单的。我们要捕捉页面事件,如当用户点击页面元素(如背景)时,引发页面元素的onclick事件。发果没有捕捉到事件,就要提升DHTML的等级,直到Document对象的最高层次。这样,我们就能捕捉到任何事件了。在VB6中,我们可以简单地用WithEvents关键词指定WebBrowser.Document到MSHTML.HTMLDocument。

在VB.NET中,这个简单方法不再有效。因为ActiveX控件创建了两个接口,两个接口中使用了同样的方法名,导致出现运行时错误。所以,你必须明确指定Document对象使用的接口,并创建事件处理句柄(呵呵,tuenhai翻译得还不错吧)。

以下是示例代码:

' IMPORTANT: this code assumes that you've added a reference to the

' Microsoft HTML Object Library type library

Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

AxWebBrowser1.Navigate("http://localhost/default.asp")

End Sub

Private Sub AxWebBrowser1_NavigateComplete2(ByVal sender As Object, _

ByVal e As AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event) Handles _

AxWebBrowser1.NavigateComplete2

' must wait for this event to grab a valid refernece to the Document

' property

Dim doc As mshtml.HTMLDocument = DirectCast(AxWebBrowser1.Document, _

mshtml.HTMLDocument)

' Cast to the interface that defines the event you're interested in

Dim docevents As mshtml.HTMLDocumentEvents2_Event = DirectCast(doc, _

mshtml.HTMLDocumentEvents2_Event)

' Define a handler to the onclick event

AddHandler docevents.onclick, AddressOf onclickproc

End Sub

' Notice that the signature of this event is different from usual, as it

' is expected to return a Boolean - if false the default effect associated

' with the event (for example, jumping to another page if the click is on

' an hyperlink) is canceled.

Private Function onclickproc(ByVal obj As mshtml.IHTMLEventObj) As Boolean

' an object on the page has been clicked - you can learn more about

' type and position of this object by querying the obj's properties

' ...

End Function

译者注:

这是tuenhai的第一篇译稿。

个人心得,近几日在国外有关程序设计网站转悠,得益良多。又想到书法学习的“取法乎上”。共享软件的出路在于走向国际。软件设计的学习又何尝不是这样呢?国际的学习资源相比国内的学习资源如何?

English决不是障碍。tuenhai不相信自己的English会比您好。初中基础,加上金山词霸即指即译,足矣。

http://www.Tuenhai.com

2004年5月16日

Tuenhai简介:Tuenhai同学对儒释道医卜命相有一定研究,对网络及英语最感兴趣,于哲学最有心得.常人利已,圣人利他,我非圣人,取道中庸.希望与各位精英交流,MSN:king#tuenhai.com

我的网站: http://www.Tuenhai.com/

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航