您的位置:首页 > 其它

GetCommandLine 分析

2015-06-27 14:06 399 查看
程序的 abc.exe

三个参数 1 2 3

1. 通过CreateProcess()调用

BOOL bRet = CreateProcess(

sCmd,

sParam,

NULL,

NULL,

FALSE,

0,

NULL,

NULL,

&si,

&pi);

(1)如果sCmd = "D:\test\abc.exe", sParam = "1 2 3", 则在abc.exe程序中通过GetCommandLine()得到字串
"1 2 3"

(2)如果sCmd = "D:\test\abc.exe",sParam = "D:\test\abc.exe 1
2 3", 则在abc.exe程序中通过GetCommandLine()得到字串 "D:\test\abc.exe 1 2 3"

(3)如果sCmd = "D:\test\abc.exe", sParam = "\"D:\test\abc.exe\"
1 2 3", 则在abc.exe程序中通过GetCommandLine()得到字串 "\"D:\test\abc.exe\" 1 2 3"

总结:[u]在使用CreateProcess()调用程序时[/u]

(1).在子进程中通过GetCommandLine()得到的命令行结果跟调用时传入的sParam完全一致。



(2).[u]方式(2)和(3)效果其实是一样的,对进程全路径文件名是否单独加引号,Windows都兼容。只是程序在使用这个参数时,要做脱引号处理。[/u]

(3).标准做法是采用方式(3),这样既可以兼容执行程序路径中包含的空格,也可以和ShellExecute()调用保持一致。





2. 通过ShellExecute()调用

(1)ShellExecute(NULL, "open", "D:\test\abc.exe", "1 2 3", "", SW_HIDE);

结果则在abc.exe程序中通过GetCommandLine()得到的字串为"\"D:\test\abc.exe\" 1
2 3",

即命令行中包含有进程名,并且程名有单独的引号引起,程序在使用该参数时要做脱引号处理。

(2)ShellExecute(NULL, "open", "D:\test\abc.exe",
"D:\\test\\abc.exe 1 2 3", "", SW_HIDE);

结果则在abc.exe程序中通过GetCommandLine()得到的字串为 "\"D:\test\abc.exe\" D:\test\abc.exe
1 2 3", ----- 这种调用是错误的

(3)ShellExecute(NULL, "open", "D:\test\abc.exe", "\"D:\\test\\abc.exe\"
1 2 3", "", SW_HIDE);

结果则在abc.exe程序中通过GetCommandLine()得到的字串为 "\"D:\test\abc.exe\" \"D:\test\abc.exe\"
1 2 3", ----- 这种调用是错误的

总结:在使用ShellExecute()调用程序时

(1).命令就是命令,参数就是参数,参数中不需要再次包含执行程序名。

(2).在子进程中通过GetCommandLine()得到的命令行参数中,总会包含有进程全路径文件名,并且是被单独引号引起的,用到时需要做脱引号处理。

(3).在子进程中[u]通过GetCommandLine()得到的命令行参数结果ShellExecute()的第五个参数lpDirectory没任何关系,调用时永远默认置空字串即可。[/u]

(4).ShellExecuteEx()与ShellExecute()的情况一样。



3. 通过abc.exe的快捷方式启动,则在abc.exe程序中通过GetCommandLine()得到字串 ""D:\test\abc.exe"
1 2 3", 注意进程名有引号



总结:在CMD命令行里面调用时,不管是否对进程名加引号,在程序里面获取到的结果,进程名都会有单独的引号引起的。

4. 通过CMD命令行调用

(1)输入 D:\test\abc.exe 1 2 3, 则在abc.exe程序中通过GetCommandLine() 得到字串
""D:\test\abc.exe" 1 2 3", 注意进程名单独有引号

(2)输入 "D:\test\abc.exe" 1 2 3, 则在abc.exe程序中通过GetCommandLine() 得到字串
""D:\test\abc.exe" 1 2 3", 注意进程名单独有引号

可见:调用时无论对进程全路径文件名是否加引号, 结果是一样, 得到的参数中进程名都有单独的引号引起的。

特别注意:

对于路径中包含空格的情况, 则调用时必须加引号, 如 "C:\Program Files\abc.exe" 1 2 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: