WebBrowser控件捕捉DHTML事件
屠恩海(SunHai)翻譯
開發工具: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對象使用的接口,并創建事件處理句柄。
以下是示例代碼:
' 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
譯者注: 這是我的第一篇譯稿。 個人心得,近幾日在國外有關程序設計網站轉悠,得益良多。又想到書法學習的“取法乎上”。共享軟件的出路在于走向國際。軟件設計的學習又何嘗不是這樣呢?國際的學習資源相比國內的學習資源如何? English決不是障礙。我不相信我的English會比您好。初中基礎,加上金山詞霸即指即譯,足矣。
|