c++ - 找到cmd.exe文件的位置

标签 c++ windows shell visual-c++

我构建了一个 C++ 程序,它依赖于“cmd.exe”来执行一些任务。 现在,出于测试目的,该文件的路径是“c:\windows\system32\cmd.exe”。 我的问题是,是否有任何 C++ API 可以返回该文件的路径,并且知道我的程序必须在 win32 和 win64 上运行。

最佳答案

GetSystemDirectory 是一种选择。对于 32 位应用程序,它将返回 32 位系统目录。对于 x64 应用程序,它将返回 64 位 native 系统目录。

您还可以将 CreateProcessShellExecuteExcmd.exe 一起使用,它应该在没有路径的情况下找到它,除非您特别关心某人操纵搜索路径并获取错误的 cmd.exe

如果您要启动 .cmd 文件,则只需使用 ShellExecuteExopen 动词即可执行此操作。通常,对于 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 of CreateProcess is that ShellExecuteEx 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/

相关文章:

c++ - Variadic 类模板和继承 - 默认编译器生成的构造函数

c++ - 使用多个着色器时的驱动程序错误

windows - 我应该如何正确使用 Git 进行 Visual FoxPro 开发?

shell - 检查PID是否僵化的可移植shell解决方案

python - 通过双击 .desktop 文件来运行 shell 脚本来启动 python 脚本

c++ - unordered_map 的问题

c++ - 使用 llvm-gcc 4.x 安装 srilm 1.6.0 时出现问题

c++ - Windows 桌面复制 API 等效 IOS

python - 尝试使用 boto3 访问 s3 存储桶,但得到 403

c - 如何像 ps -e 一样显示进程