[UMU WSH 教程](10)常见对象 - WScript.Shell
在《[UMU WSH 教程](2)输入》提到的使用 IE 做输入密码的界面,《[UMU WSH 教程](7)WScript 对象》提到的 WScript.CreateObject 和 VBS 语言自带的 CreateObject 函数是不一样的,现在做详细解释。
WScript.CreateObject 的定义是:function CreateObject(ProgID:BSTR; Prefix:BSTR): IDispatch;,CreateObject 的定义是:function CreateObject(ProgID:BSTR; Location:BSTR): IDispatch;,Prefix 是一个前缀,有些对象会触发事件,需要通过这个前缀找到事件处理函数,而 Location 是指定对象所在的网络服务器,属于 DCOM 的概念,对象的服务组件在远程机器上的,Location 是一个机器名。
用 IE 为例,当用户关闭 IE 的时候,会触发 OnQuit 事件,我们可以通过 Prefix 指定一个处理过程来处理 IE 的 OnQuit 事件,例如:
Set objIEA = WScript.CreateObject( "InternetExplorer.Application", "UMU_" )
...
Sub UMU_OnQuit()
MsgBox "Quiting..."
WScript.Quit
End Sub
关闭 IE 时,UMU_OnQuit 过程会被调用,先是一个 MsgBox 提示,然后退出脚本程序。
使用 IE 做输入密码的界面的大概过程:创建 InternetExplorer.Application 对象,初始化,浏览 about:blank,获得 Document 对象,往 Document 里写入 HTML 代码创建一个密码框和一个按钮,按钮的点击处理过程由 VBS 代码提供,VBS 代码负责读出密码并关闭 IE 对象。
不过由于 HTML 代码可能比较长,混合在 VBS 代码里看起来不美观,所以一般是分开,一个 .HTM 和一个 .VBS,这样的话就不需要往 Document 里写入 HTML 代码了,而是直接让 IE 对象去浏览我们的 .HTM 文件。以下示例代码出自微软脚本中心的文章《如何使用 InputBox 来屏蔽密码?》。
第一项操作是将以下内容保存为 C:\Scripts\Password.htm(是的,我们要将其保存为 HTML 页):
<SCRIPT LANGUAGE="VBScript">Sub RunScript OKClicked.Value = "OK"End SubSub CancelScript OKClicked.Value = "Cancelled"End Sub</SCRIPT><BODY><font size="2" face="Arial">Password: </font><font face="Arial"><input type="password" name="UserPassword" size="40"></font></p><input type="hidden" name="OKClicked" size = "20"><input id=runbutton class="button" type="button" value=" OK " name="ok_button" onClick="RunScript"> <input id=runbutton class="button" type="button" value="Cancel" name="cancel_button" onClick="CancelScript"></BODY>
第二项操作是将以下代码保存为 .vbs 文件(例如,Password.vbs):
On Error Resume NextSet objExplorer = WScript.CreateObject _ ("InternetExplorer.Application", "IE_")objExplorer.Navigate "file:///C:\Scripts\password.htm"objExplorer.ToolBar = 0objExplorer.StatusBar = 0objExplorer.Width = 400objExplorer.Height = 350 objExplorer.Left = 300objExplorer.Top = 200objExplorer.Visible = 1Do While (objExplorer.Document.Body.All.OKClicked.Value = "") Wscript.Sleep 250Loop strPassword = objExplorer.Document.Body.All.UserPassword.ValuestrButton = objExplorer.Document.Body.All.OKClicked.ValueobjExplorer.QuitWscript.Sleep 250If strButton = "Cancelled" Then Wscript.QuitElse Wscript.Echo strPasswordEnd If那么,接下来该做什么呢?启动 Password.vbs。在执行此操作时,屏幕上会弹出一个带有密码框的 Web 页。如果键入密码并单击“OK”,所键入的密码将回显在屏幕上(同样只是为了说明确实捕获到了键入的密码)。如果单击“Cancel”,脚本将会结束执行。