帮助我理解代码中的问题
#include <Windows.h>
#include <iostream>
int main()
{
STARTUPINFO si;
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
//TCHAR cmd[] = TEXT(R"("c:\Program Files\Internet Explorer\iexplore.exe")");
TCHAR cmd[] = TEXT(R"("c:\Program Files(x86)\Windows Media Player\wmplayer.exe")");
BOOL res = ::CreateProcess(nullptr, cmd, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi);
//iexplore - run ok, wmplayer - false & getlasterror = 2
return 0;
}
我的问题是什么?
PS:Windows 10,Visual Studio 2017 CE,平台工具集v141
不要硬编码系统文件夹和系统应用程序的路径。(这可能会导致不同机器/不同时间出错或拼写错误。)
@Remy Lebeau提到,你可以使用SHGetFolderPath()
或SHGetKnownFolderPath()
来获得正确的Program Files
路径。或者你可以从注册表中获得真正的路径。
这是我们可以摆脱硬代码路径的另一种简单方法。 iexplore
和wmplayer
都是windows中的应用程序。您可以在命令行(start appname
)中使用“cmd.exe
”启动它,或者使用如下代码:
#include <Windows.h>
#include <iostream>
int main()
{
STARTUPINFO si;
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
//TCHAR cmd[] = TEXT("cmd /c start iexplore");
TCHAR cmd[] = TEXT("cmd /c start wmplayer");
BOOL res = ::CreateProcess(NULL, cmd, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi);
return 0;
}
编辑:
或者你可以使用ShellExecute/Ex
而无需启动cmd
而不是CreateProcess
:
ShellExecuteA(NULL,NULL, "wmplayer",NULL, NULL, SW_NORMAL);