VBS基础篇 vbscript Sendkeys模拟键盘操作
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
VBS基础篇vbscript Sendkeys模拟键盘操作
vbscript中我们可以使用object.SendKeys模拟键盘操作,将一个或多个按键指令发送到指定Windows窗口来控制应用程序运行。
其使用格式为:object.SendKeys(string)
object:表示WshShell对象
string:表示要发送的按键指令字符串,需要放在英文双引号中。WshShel l.SendKeys “string”
1、基本键
一般来说,要发送的按键指令都可以直接用该按键字符本身来表示,例如要发送字母"x",使用WshShell.SendKeys "x" 即可。也可直接发送多个按键指令,只需要将按键字符按顺序排列在一起即可。例如,要发送按键"cfan",可以使用WshShell.SendKeys "cfan"
2、特殊功能键
对于需要与Shift、Ctrl、Alt三个控制键组合的按键SendKeys使用特殊字符来表示:
Shift +
Ctrl ^
Alt %
具体如下:
Shift ---------WshShell.SendKeys "+"
Ctrl---------WshShell.SendKeys "^"
Alt---------WshShell.SendKeys "%"
由于“+”、“^”这些字符用来表示特殊的控制按键了,如何表示这些按键呢?只要用大括号括住这些字符即可。例如: 要发送加号“+”,可使用“WshSh ell.SendKeys "{+}"”
另外对于一些不会生成字符的控制功能按键,也同样需要使用大括号括起来按键的名称。
例如要发送回车键,需要用“WshShell.SendKeys "{ENTER}" ”表示;
发送向下的方向键用“Wshell.SendKeys "{DOWN}" ”表示
Space---------WshShell.SendKeys " "
Enter---------WshShell.SendKeys "{ENTER}"
←---------WshShell.SendKeys "{RIGHT}"
↑---------WshShell.SendKeys "{UP}"
F1---------WshShell.SendKeys "{F1}"
常见按键代码:
如果需要发送多个重复的单字母按键,不必重复输入该字母,SendKeys允许使用简化格式进行描述,使用格式为“{按键数字}”。例如要发送10个字母“x”,则输入“WshShell.SendKeys"{x 10}"”即可
3、组合按键
如要发送的组合按键是同时按下Ctrl+E,需要用WshShell.SendKeys "^e " 表示,如果要发送的组合按键是按住Ctrl键的同时按下E与C两个键,这时应使用小括号把字母括起来,书写格式为WshShell.SendKeys "^(ec)" 这里要注意它与WshShell.SendKeys "^ec" 的区别,后者表示组合按键是同时按住C trl和E键,然后松开Ctrl键,单独按下"C"字母键。
由于"+"、"^" 这些字符用来表示特殊的控制按键了,如何表示这些按键呢?只要用大括号括住这些字符即可。例如,要发送加号"+",可使用WshShel l.SendKeys "{+}" 。另外对于一些不会生成字符的控制功能按键,也同样需要使用大括号括起来按键号名称,例如要发送回车键,需要用WshShell.SendKey s "{ENTER}" 表示,发送向下的方向键用WshShell.SendKeys "{DOWN}" 表示。
4、多个重复的按键
如果需要发送多个重复的单字母按键,不必重复输入该字母,SendKdys允许使用简化格式进行描述,使用格式为"{按键数字}"。例如要发送10个字母"x",则输入WshShell.SendKeys "{x 10}" 即可。
看一下实例:
例1:2秒后按下F5刷新桌面
'sleep单位是毫秒;1秒=1000毫秒;10分钟=600000毫秒
Dim WshShell,Path,i
Set WshShell = Wscrpt.CreateObject("Wscrpt.Shell")
Wscrpt.Sleep 2000
WshShell.SendKeys "{F5}"
例2:电脑自动重启
Dim WshShell
Set WshShell = CreateObject("Wscrpt.Shell")
WshShell.SendKeys "^{ESC}u"
WshShell.SendKeys "R"
例3:启动任务管理器
Dim WshShell
Set WshShell = CreateObject("Wscrpt.Shell")
WshShell.SendKeys "^+{ESC}"
例4:自动关机
Dim WshShell
Set WshShell=Wscrpt.CreateObject("Wscrpt.Shell")
Wscrpt.Sleep 2000
WshShell.Run "shutdown -r -t 120"
wscrpt.sleep 6000
WshShell.Run "shutdown -a"
例5:在记事本中输入Happy Birthday!并保存为birth.txt Dim WshShell
Set WshShell=Wscrpt.CreateObject("Wscrpt.Shell")
WshShell.Run "notepad"
Wscrpt.Sleep 1500
WshShell.AppActivate "Ξ? - ?±"
WshShell.SendKeys "Happy Birthdy!!!"
Wscrpt.Sleep 500