对编写脚本熟悉的读者都知道页面中可以添加脚本响应元素的事件,例如超链接的onclick事件,图片的onmousemove事件,我们也可以使vb程序响应这些事件。下面是一个vb响应页面中按钮的click事件的代码:
首先建立一个新工程,在form1中加入一个webbrowser控件,然后在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 object, url as variant)
'建立事件响应类
dim cfforward as clsforward
'定义在浏览器中显示的html代码,其中包含一个按钮btnmybutton
dim shtml as string
shtml = "<p>this is some text.</p>"
shtml = shtml & "<p>and here is a button.</p>"
shtml = shtml & "<button id=btnmybutton>"
shtml = shtml & "click this button.</button>"
'将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”按钮。程序就会弹出消息框提示“你点击了按钮.”
www.applevb.com