監控網頁中元素的事件 (轉)

gugu99發表於2008-01-09
監控網頁中元素的事件 (轉)[@more@]

對編寫指令碼熟悉的讀者都知道頁面中可以新增指令碼響應元素的事件,例如超連結的OnClick事件,圖片的OnMouseMove事件,我們也可以使VB響應這些事件。下面是一個VB響應頁面中按鈕的Click事件的程式碼:
首先建立一個新工程,在Form1中加入一個browser,然後在Form1中加入以下程式碼:

Option Explicit

Public Sub Some_Procedure()
MsgBox "你點選了按鈕."
End Sub

Private Sub Form_Load()
'空頁面
WebBrowser1.Navigate2 "about:blank"
End Sub

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As , URL As Variant)
'建立事件響應類
Dim cfForward As clorward

'定義在中顯示的HTML程式碼,其中包含一個按鈕btnMyButton
Dim sHTML As String
sHTML = "

This is some text.

"
sHTML = sHTML & "

And here is a button.

"
sHTML = sHTML & ""

'將HTML程式碼寫入瀏覽器
WebBrowser1.Document.body.innerHTML = sHTML

'將事件響應類連線到頁面的按鈕btnMyButton上
Set cfForward = New clsForward
cfForward.Set_Destination Me, "Some_Procedure"
WebBrowser1.Document.All("btnMyButton").onclick = cfForward
End Sub

向工程中新增一個Class Module,Class Module的Name屬性設定為clsForward,在clsForward中新增以下程式碼:

Option Explicit

Dim oObject As Object
Dim sMethod As String
Dim bInstantiated As Boolean

Private Sub Class_Initialize()
bInstantiated = False
End Sub

Public Sub Set_Destination(oInObject As Object, sInMethod As String)
Set oObject = oInObject
sMethod = sInMethod
bInstantiated = True
End Sub

Public Sub My_Default_Method()
If bInstantiated Then
CallByName oObject, sMethod, VbMethod
End If
End Sub

在執行前,你需要吧My_Default_Method設定為預設過程,方法是:在clsForward模組的程式碼視窗中將游標定位到My_Default_Method中,然後選擇選單 Tools | Procedure Attributes。然後在彈出視窗中點選advanced按鈕,然後在procedure id下拉框中選擇[Default]


執行程式,點選Webbrowser中的“Click this button”按鈕。程式就會彈出訊息框提示“你點選了按鈕.”

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-996953/,如需轉載,請註明出處,否則將追究法律責任。

相關文章