C++:如何让我的程序打开一个带有可选参数的 .exe [英] C++: How to make a my program open a .exe with optional args
问题描述
我在使用程序时遇到了一些问题.我的目标是让它打开几个 .exe 文件,并传递可选的 args.例如,如果我想打开一个 pdf,我可以在 cmd 窗口中输入下面的字符串.
I'm having some trouble with a program. My goal is to have it open several .exe files with optional args passed. For example if I wanted to open up a pdf I could type the string below into a cmd window.
// 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,但当然不会加载文件.第二个根本不起作用.
Here are two tries I used. The first opens the PDF but of course doesn't load the file. The second simply doesn't work.
// 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\"");
我不确定第二个不起作用的原因.可能是我对系统有误解,或者我没有正确使用分隔符.
I'm unsure of the reason why the second one does not work. It could be I'm misunderstanding something about system, or I'm not using delimiters right.
我觉得有一个专门为此设计的库,而不是创建一个使用这么多分隔符的长字符串.
I feel like there is a library out there designed for this rather than creating a long string that uses so many delimiters.
感谢您的帮助.
推荐答案
欢迎使用 Stack Overflow!
Welcome to Stack Overflow!
system 方法通过将其参数传递给 cmd/c 来工作.因此,您将需要一组额外的引号.请参阅 sled 发布的相关问题.
The system method works by passing it's argument to cmd /c. So you will need an extra set of quotes around it. See related question posted by sled.
作为系统的替代,看看ShellExecute 或 ShellExecuteEx Win32 API 函数.虽然不那么便携,但它有更多的功能.
As an alternative to system, take a look at the ShellExecute or ShellExecuteEx Win32 API function. It has more features although it is not as portable.
// 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();
更多信息这里.
这篇关于C++:如何让我的程序打开一个带有可选参数的 .exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!