C++:如何使我的程序打开带有可选参数的.exe

标签 c++ windows system

我在使用程序时遇到了一些问题。我的目标是让它打开几个带有可选参数的 .exe 文件。例如,如果我想打开一个 pdf,我可以在 cmd 窗口中输入下面的字符串。

// If used in a cmd window it will open up my PDF reader and load MyPDF.pdf file
"c:\Test space\SumatraPDF.exe" "c:\Test space\Sub\MyPDF.pdf"

这是我用过的两个尝试。第一个打开 PDF,但当然不会加载文件。第二个根本行不通。

// Opens the PDF in my program
system("\"C:\\Test space\\SumatraPDF.exe\"");

// Error I get inside of a cmd window is the comment below
// 'C:\Test' is not recognized as an internal or external command, operable program or batch file.
//system("\"C:\\Test space\\SumatraPDF.exe\" \"C:\\Test space\\Sub\\MyPDF.pdf\"");

我不确定第二个不起作用的原因。可能是我对系统有一些误解,或者我没有正确使用定界符。

我觉得有一个专门为此设计的库,而不是创建一个使用这么多分隔符的长字符串。

感谢您的帮助。

最佳答案

欢迎来到 Stack Overflow!

系统方法通过将其参数传递给 cmd/c 来工作。所以你需要在它周围加上一组额外的引号。参见 related question雪橇发布。

作为系统的替代品,请查看 ShellExecuteShellExecuteEx Win32 API 函数。它具有更多功能,但不那么便携。

// ShellExecute needs COM to be initialized
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

SHELLEXECUTEINFO sei = {0};
sei.cbSize = sizeof(sei);
sei.lpFile = prog;   // program like c:\Windows\System32\notepad.exe
sei.lpParameters = args;  // program arguments like c:\temp\foo.txt
sei.nShow = SW_NORMAL;  // app should be visible and not maximized or minimized

ShellExecuteEx(&sei);  // launch program

CoUninitialize();

更多信息 here .

关于C++:如何使我的程序打开带有可选参数的.exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7669433/

相关文章:

.net - 托管 C++/CLI 中的 System::String 连接

c++ - C++ 中的 system() 函数在一段时间内工作正常,但由于 ECHILD 错误而在一段时间内失败返回 -1。为什么?

c++ - 结构 vector 内部的结构 vector

c++ - 在for循环C++中调用Void函数

c++ - 为什么 decltype(auto) 不能按预期工作?

windows - 处理文件名中的特殊字符时批量重命名问题

c - Windows API MoveFile() 不适用于运行 exe

windows - 'jmeter' 不是内部或外部命令,也不是可运行的程序或批处理文件

c - C上的系统编程

c++ - 重载 == 运算符导致丢弃限定符错误