在Windows侧边栏工具开发时,想做一个和Windows一样的功能,基本上是以下两个功能:
1. 可以直接运行系统Path环境变量中列出路径下的程序
2. 可以直接运行UNC地址,URL网址和FTP地址,即支持常见的网络协议访问方式
其实gadget开发API中已有函数支持此功能的函数,只不过我开始选错了,我开始用的是
var winShell = new ActiveXObject("Shell.Application");
winShell.ShellExecute("\""+q+"\"");
winShell = null;
发现该方法只能运行程序,但是不支持参数传递,幸好有找到个替代产品,System.Shell.execute(appPath, null, null, open);
函数原型定义为:
execute MethodLaunches an application.
Syntax
System.Shell.execute(strFile [, strArgs] [, strDir] [, strOperation])Parameters
strFile
Required. String that specifies a Universal Naming Convention (UNC) path to an executable file, a filename, or a URL.
strArgs
Optional. If strFile specifies an executable file then String specifies the parameters to be passed to the application. For example, a UNC path such as
System.Gadget.path + "\\MyFile.Txt"
.Note If strFile specifies a filename or URL, strArgs is unneccessary and should be blank, null, or an empty string.strDir
Optional. String that specifies the UNC path for the default (working) directory of the executable file.
strOperation
Optional. String that specifies the action (or Microsoft Windows Shell verb) to be performed. The set of available verbs depends on the particular file or folder.
edit
- Opens the file specified by strArgs for editing.
explore
- Opens the folder specified by strDir for exploring.
find
- Opens the folder specified by strDir for searching.
open
- Opens the file specified by strArgs.
- Prints the file specified by strArgs on the default printer.
Return Value
No return value.
Remarks
Supplying a path to a filename (with extension) or a URL for strFile will launch the default application associated with that file extension and load the filename specified.
Note Alternatively, a path to a known application .exe can by supplied for strFile while strArgs, strDir, and strOperation are used to specify the rest of the file information.strArgs, strDir, and strOperation can be assigned values in combination as required.
UNC paths should escape special characters with a '\'.
System.Shell.execute第一个参数是应用程序的路径,第二个参数是参数列表,第三个参数是应用程序工作目录,第四个是打开方式。
用上这个函数实现运行栏的功能还需要做一个命令行的解析工作,由于gadget工作在页面中,用javascript进行解析需要正则表达式来识别应用程序路径和参数列表,代码如下:
现在命令行解析有了,执行命令也有了,就可以接收 command.exe args[] 这样的输入格式了,正则表达式将第一个出现的边界类字符串作为命令或程序路径的结束位置,后面所以的字符串作为命令的参数。function retApp(str, retPart){
var s = str;
var re = new RegExp("[ \f\n\r\t\v]*(\".+\")|([^ \f\n\r\t\v]+)","ig");
var arr = re.exec(s);
if (retPart == 0) {
return(RegExp.lastMatch);
} else {
return(RegExp.rightContext);
}
return("");
}System.Shell.execute(retApp(q, 0), retApp(q, 1), null, open);