作者: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會比您好。初中基礎,加上金山詞霸即指即譯,足矣。
新聞熱點
疑難解答