将路径传递给CreateProcessA

时间:2012-06-19 08:01:37

标签: c++ c winapi

我有一个函数,它读取注册表项,获取程序的路径,并使用此路径作为第二个参数调用CreateProcessA。调试应用程序时,它无法说找不到该文件。

a)是的,该文件存在 b)是的,我有权执行文件

问题:实际读取reg键并给出CreateProcessA路径的函数不会转义路径:这意味着,CreateProcessA接收的字符串如“C:\ Program Files \ prog.exe”而不是“ C:\\ Program Files \\ prog.exe“。那是问题吗?是否存在任何Windows函数自动转义所有反斜杠?

1 个答案:

答案 0 :(得分:0)

常见错误包括未指定可执行文件的路径作为CreateProcess的第一个参数,而不是在第二个参数中引用可执行文件的路径

CreateProcess( <exe path goes here> , <quoted exe path plus parameters goes here>, ... );

像这样:

std::wstring executable_string(_T("c:\\program files\\myprogram\\executable.exe"));
std::wstring parameters(_T("-param1 -param2"));

wchar_t path[MAX_PATH+3];
PathCanonicalize(path, executable_string.c_str());
path[sizeof(path)/sizeof(path[0]) - 1] = _T('\0');

// Make sure that the exe is specified without quotes.
PathUnquoteSpaces(path);
const std::wstring exe = path;

// Make sure that the cmdLine specifies the path to the executable using
// quotes if necessary.
PathQuoteSpaces(path);
std::wstring cmdLine = path + std::wstring(_T(" ")) + parameters;

BOOL res = CreateProcess(
                 exe.c_str(),
                 const_cast<wchar_t *>(cmdLine.c_str()),
                 ...);

我只是复制并改编了一些,所以上面可能会有一些错误,但这个想法就在那里。确保在第一个参数中使用没有引号的路径,在第二个参数中使用带引号的路径,你应该没问题。

相关问题