如何在 Windows 7 系统中向用户显示一个用来选择文件的对话框呢
相信很多人都看过“嗨,Scripting Guy!”上面的一个问题,就算没有看过原文,也应该看过被复制粘贴后的代码。
我如何向用户显示一个用来选择文件的对话框?
问:嗨,Scripting Guy!有没有什么方法可以让我使用脚本向用户显示一个对话框,供用户选择文件使用? — BF
答:您好,BF。如果您使用的是 Windows 2000,我们不知道实现此操作的方法,至少操作系统中没有内置这样的方法。但如果您使用的是 Windows XP,情况就不同了。在 Windows XP 上,您可以使用“UserAccounts.CommonDialog”对象向用户显示一个标准的“文件打开”对话框。可以用类似以下代码的脚本:
代码我就不复制粘贴了,原文里面有,网上也到处都是。但是问题在于,这段代码只能用于 Windows XP 系统(Windows 2003 或许也可以,但是我没有测试过),而现在 Windows 7 已经逐渐开始流行起来。在 Vista 和Windows 7 系统中默认是不自带 UserAccounts.CommonDialog 组件的(顺便提一句,SAFRCFileDlg.FileOpen 和 SAFRCFileDlg.FileSave 组件也是没有的)。
那么如何在 Windows 7 系统中向用户显示一个用来选择文件的对话框呢?答案是 html 中的文件选择对话框:
| Function BrowseForFile() | | Dim shell : Set shell = CreateObject("WScript.Shell") | | Dim fso : Set fso = CreateObject("Scripting.FileSystemObject") | | | | Dim tempFolder : Set tempFolder = fso.GetSpecialFolder(2) | | Dim tempName : tempName = fso.GetTempName() | | Dim tempFile : Set tempFile = tempFolder.CreateTextFile(tempName & ".hta") | | | | tempFile.Write _ | | "<html>" & _ | | "<head>" & _ | | | | "<title>Browse</title>" & _ | | "</head>" & _ | | "<body>" & _ | | | | "<input type='file' id='f' />" & _ | | "<script type='text/javascript'>" & _ | | "var f = document.getElementById('f');" & _ | | | | "f.click();" & _ | | "var shell = new ActiveXObject('WScript.Shell');" & _ | | "shell.RegWrite('HKEY_CURRENT_USER\\Volatile Environment\\MsgResp', f.value);" & _ | | "window.close();" & _ | | | | "</script>" & _ | | "</body>" & _ | | "</html>" | | | | tempFile.Close | | shell.Run tempFolder & "\" & tempName & ".hta", 0, True | | BrowseForFile = shell.RegRead("HKEY_CURRENT_USER\Volatile Environment\MsgResp") | | | | shell.RegDelete "HKEY_CURRENT_USER\Volatile Environment\MsgResp" | | End Function | | | | | | | | | | | | path = BrowseForFile() | | If path <> "" Then WScript.Echo pathCOPY |
原文:http://demon.tw/programming/vbs-open-file-dialog.html |