考虑以下代码及其可执行文件- runner.exe
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = NULL;
shExecInfo.hwnd = NULL;
shExecInfo.lpVerb = "open";
shExecInfo.lpFile = argv[1];
string Params = "";
for ( int i = 2; i < argc; ++i )
Params += argv[i] + ' ';
shExecInfo.lpParameters = Params.c_str();
shExecInfo.lpDirectory = NULL;
shExecInfo.nShow = SW_SHOWNORMAL;
shExecInfo.hInstApp = NULL;
ShellExecuteEx(&shExecInfo);
return 0;
}这两个批处理文件都执行它们应该做的事情,即运行notepad.exe和运行notepad.exe,并告诉它尝试打开test.txt:
1.
runner.exe notepad.exe
2.
runner.exe notepad.exe test.txt现在,考虑一下这个批处理文件:
3.
runner.exe runner.exe notepad.exe这个应该运行runner.exe并将notepad.exe作为其命令行参数之一发送,不是吗?然后,第二个runner.exe实例应该运行notepad.exe --这不会发生,我会得到一个“notepad.exe无法找到'am‘。请确保您键入的名称正确,然后再试一次”错误。如果我打印argc参数,它是14,用于runner.exe的第二个实例,它们都是奇怪的东西,比如Files\Microsoft、SQL、Files\等等。我搞不懂为什么会这样。我希望能够尽可能多地使用命令行参数或至少2来字符串runner.exe调用。
我正在使用Windows 7,如果这有区别的话。
发布于 2010-03-15 17:42:42
在这一行中有一个bug:
Params += argv[i] + ' ';这将将32添加到指针argv[i],这不是您想要的。您可以将其分为两行:
Params += argv[i];
Params += ' ';或使用:
Params += string(argv[i]) + ' ';您还可能希望在每个参数周围添加引号,以防它包含空格。
我还将fMask设置为SEE_MASK_NOASYNC,因为MSDN声明:
在调用
后立即退出的ShellExecuteEx应用程序应该指定此标志.
发布于 2010-03-15 17:44:05
问题是这条线:
Params += argv[i] + ' '因为argv[i]的类型是char *,将32添加到argv[i],所以会给出一个指向随机内存中间的指针。
我要把它改写为:
Params += std::string(argv[i]) + ' ';或者,如果您想做得很好,您可以修改它,只在需要的时候添加一个空格:
for ( int i = 2; i < argc; ++i )
{
if (!Params.empty())
Params += ' ';
Params += argv[i];
}发布于 2010-03-15 17:52:49
我认为问题在于如何为下一个调用创建命令行参数:
Params += argv[i] + ' ';不像预期的那样工作。试一试以下几点:
#include <windows.h>
#include <fstream>
#include <iostream>
#include <tchar.h>
using namespace std;
#ifdef _UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif
int _tmain(int argc, TCHAR *argv[])
{
{
std::ofstream f("C:\\output.txt", std::ios::app);
f << "app called" << std::endl;
}
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = NULL;
shExecInfo.hwnd = NULL;
shExecInfo.lpVerb = _T("open");
shExecInfo.lpFile = argv[1];
tstring Params(_T(""));
for ( int i = 2; i < argc; ++i )
{
Params += argv[i];
Params += _T(' ');
}
shExecInfo.lpParameters = Params.c_str();
shExecInfo.lpDirectory = NULL;
shExecInfo.nShow = SW_SHOWNORMAL;
shExecInfo.hInstApp = NULL;
ShellExecuteEx(&shExecInfo);
return 0;
}https://stackoverflow.com/questions/2448802
复制相似问题