我构建了一个 C++ 程序,它依赖于“cmd.exe”来执行一些任务。 现在,出于测试目的,该文件的路径是“c:\windows\system32\cmd.exe”。 我的问题是,是否有任何 C++ API 可以返回该文件的路径,并且知道我的程序必须在 win32 和 win64 上运行。
最佳答案
GetSystemDirectory
是一种选择。对于 32 位应用程序,它将返回 32 位系统目录。对于 x64 应用程序,它将返回 64 位 native 系统目录。
您还可以将 CreateProcess
或 ShellExecuteEx
与 cmd.exe
一起使用,它应该在没有路径的情况下找到它,除非您特别关心某人操纵搜索路径并获取错误的 cmd.exe
。
如果您要启动 .cmd
文件,则只需使用 ShellExecuteEx
和 open
动词即可执行此操作。通常,对于 Windows 桌面应用程序,建议使用 ShellExecuteEx 来启动其他程序。例如,以下代码将启动运行 test.cmd
脚本的命令提示符并等待结果:
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"shell32.lib")
void main()
{
SHELLEXECUTEINFOW info = {};
info.cbSize = sizeof( info );
info.lpVerb = L"open";
info.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
info.lpFile = L"test.cmd";
info.lpParameters = nullptr; // Command-line parameters
info.lpDirectory = nullptr; // Working directory to set
info.nShow = SW_SHOW;
if( !ShellExecuteExW( &info ) )
{
printf("ERROR\n");
}
else
{
// Wait for process to finish.
WaitForSingleObject( info.hProcess, INFINITE );
// Return exit code from process
DWORD exitcode;
GetExitCodeProcess( info.hProcess, &exitcode );
CloseHandle( info.hProcess );
printf("Finished with exit code %u\n", exitcode);
}
}
您还可以使用:
info.lpFile = L"cmd.exe";
info.lpParameters = L"/c test.cmd";
The primary reason to use
ShellExecuteEx
instead ofCreateProcess
is thatShellExecuteEx
can handle admin elevation requests for exes with the proper manifest elements.CreateProcess
would fail if the target EXE requires higher privileges than your current process.
关于c++ - 找到cmd.exe文件的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39990900/