提醒:本页面将不再更新、维护或者支持,文章、评论所叙述内容存在时效性,涉及技术细节或者软件使用方面不保证能够完全有效可操作,请谨慎参考!

有时候利用了COM组件的脚本可以变得很强大,比如我们可以用它实现所有需要编程编译为本机代码(*.EXE)才能实现的功能。今天要介绍的就是如何让VBScript脚本利用WScript.Shell组件在桌面上创建快捷方式。

实现代码:

Option Explicit

Dim wshShell, Shortcut
Dim strDir, strName
strDir = "D:\"
strName = "命令提示符"

Set wshShell = WSH.CreateObject("WScript.Shell")
  Set Shortcut = wshShell.CreateShortcut(strDir &_
    "\" & strName & ".lnk")
    Shortcut.TargetPath = "C:\Windows\System32\cmd.exe"
    Shortcut.WindowStyle = 1
    Shortcut.Hotkey = "CTRL+ALT+U"
    Shortcut.Description = "这是命令提示符程序描述"
    Shortcut.WorkingDirectory = strDir
    Shortcut.Save
  Set Shortcut = Nothing
Set wshShell = Nothing

运行上述代码后,你将会发现D盘的根目录下建立了一个命令提示符的快捷方式,简单解释一下上面的代码,首先strDir保存的是创建快捷方式的目录路径,strName保存的是快捷方式的名称,大家会发现在稍后的代码中,利用了WScript.Shell的CreateShortcut方法创建了以strDir + strName + ".lnk"为参数的快捷方式,注意这里快捷方式都是以lnk为扩展名的,不过单单是利用CreateShortcut方法还不能创建,我们还要进行快捷方式的配置,然后调用Save方法才能真正保存并创建一个快捷方式,大家可以对任意的快捷方式右击,查看其属性,就可以知道是哪些配置了,这里的一些配置有TargetPath指向路径、WindowStyle窗口模式、HotKey快捷热键、Description鼠标放上去出现的描述提示、WorkingDirectory工作路径等等,关于WindowStyle的值,可以参考 《WindowStyle Property》

到这里大家可能会发觉在D盘创建快捷方式貌似意义不大,比如我们想将快捷方式创建到桌面上,那么该怎么办呢?看下面这段代码:

Option Explicit

Dim wshShell, Shortcut
Dim strDir, strName
strName = "命令提示符"

Set wshShell = WSH.CreateObject("WScript.Shell")
  strDir = wshShell.SpecialFolders("Desktop")
  Set Shortcut = wshShell.CreateShortcut(strDir &_
    "\" & strName & ".lnk")
    Shortcut.TargetPath = "C:\Windows\System32\cmd.exe"
    Shortcut.WindowStyle = 1
    Shortcut.Hotkey = "CTRL+ALT+U"
    Shortcut.Description = "这是命令提示符程序描述"
    Shortcut.WorkingDirectory = strDir
    Shortcut.Save
  Set Shortcut = Nothing
Set wshShell = Nothing

恩,是的,我们利用了WScript.Shell的另外一个功能,那就是获得特殊目录路径SpecialFolders,我们这里尝试获取的是桌面的路径位置,然后将其赋值给strDir,然后接下来大家都晓得怎么做吧。