VBS SendKeys 基础用法与特殊字符处理
代码示例如下:
' ======================================
' VBS 中使用 SendKeys 模拟键盘按键输入
' 日期:2009-07-26
' 作者:刘林
' ======================================
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd"
' 脚本暂停执行 1000 毫秒(即 1 秒),等待前一条命令完成后再继续
WScript.Sleep 1000
' 注意:发送普通字符时,当前输入法必须处于英文状态
' 发送分号字符
WshShell.SendKeys ";"
WScript.Sleep 1000
' 发送冒号字符
WshShell.SendKeys ":"
WScript.Sleep 1000
' 发送双引号 -- 利用 Chr 函数将 ASCII 码转换为对应字符
WshShell.SendKeys Chr(34)
WScript.Sleep 1000
' 发送包含双引号的字符串内容
WshShell.SendKeys Chr(34) & "this is a string" & Chr(34)
WScript.Sleep 1000
' 重要提示:此为模拟物理击键,因此不支持直接发送中文
' WshShell.SendKeys Chr(34) & "这是一个字符串" & Chr(34)
WScript.Sleep 1000
' ================================================
' 如何模拟回车键、上档键(Shift)和 Alt 键?
' ================================================
' 模拟回车键:使用 {enter} 表示发送 Enter 键
WshShell.SendKeys "this is a enter!{enter}"
WScript.Sleep 1000
' 模拟上档键 Shift:使用 + 代表 Shift 键
WshShell.SendKeys "this is +a" ' 输出结果为 this is A
WScript.Sleep 1000
' 模拟 Alt 键:使用 % 代表 Alt 键
WshShell.SendKeys "this is %{TAB}" ' 输出结果触发窗口切换
WScript.Sleep 1000
' ===========================================================
' 那么如何发送 %, +, ^ 这些本身具有特殊含义的字符呢?
WshShell.SendKeys "this is {+}{^}{%}" ' 输出结果为 literal 字符而非功能键
WScript.Sleep 1000
' 此时你可能已明白:发送具有特殊意义的字符时,请将其包裹在 {} 中
' ===========================================================
' ======================================
' 更多详细信息请参阅 VBS 帮助文档 2009-07-26
' ======================================