c++ 我不能在ShellExecuteA命令中概括路径

njthzxwz  于 4个月前  发布在  Shell
关注(0)|答案(1)|浏览(71)

如果我输入用户名,它就能工作。但是如果我像下面这样运行它,它就什么也做不了。它应该能在Windows 10/11上工作;我也是一个初学者,如果我能得到任何关于使用ShellExecuteA的信息,我会很感激。

ShellExecuteA(NULL, "open", "rundll32.exe", "\"C:\\Program Files\\Windows Photo Viewer\\PhotoViewer.dll\", ImageView_Fullscreen C:\\Users\\%USERNAME%\\Downloads\\[image name].png", NULL, SW_HIDE);

字符串
这应该是在Windows图像查看器中打开所述图像。如果我把我的实际用户名而不是%USERNAME%,它就会打开。
至于我的目的,我想做一个C++程序,下载一张照片(得到的工作),然后打开它;

kg7wmglp

kg7wmglp1#

你不能在Shell API(或大多数其他文件API)使用的文件路径中使用环境变量,就像你试图做的那样。你必须首先使用ExpandEnvironmentStrings(),例如:

const char* cmdEnv = "\"%PROGRAMFILES%\\Windows Photo Viewer\\PhotoViewer.dll\", ImageView_Fullscreen C:\\Users\\%USERNAME%\\Downloads\\[image name].png";

DWORD len = ExpandEnvironmentStringsA(cmdEnv, nullptr, 0);
std::string cmd(len, '\0');
ExpandEnvironmentStringsA(cmdEnv, cmd.data(), len);

ShellExecuteA(NULL, "open", "rundll32.exe", cmd.c_str(), nullptr, SW_HIDE);

字符串
也就是说,你真的不应该硬编码任何涉及系统定义的文件夹的文件路径,比如用户配置文件,因为这些文件夹的实际位置在不同的系统中可能会有所不同。相反,你应该使用SHGetFolderPath()SHGetKnownFolderPath来获取所需文件夹的实际路径(在本例中为FOLDERID_Downloads),然后根据需要追加到它。
举例来说:

std::wstring GetKnownFolderPath(KNOWNFOLDERID folderID)
{
    PWSTR pPath = nullptr;
    SHGetKnownFolderPath(folderID, 0, nullptr, &pPath);
    std::wstring str = pPath;
    CoTaskMemFree(pPath);
    return str;
}

std::wstring cmd = L"\"" + GetKnownFolderPath(FOLDERID_ProgramFiles) + L"\\Windows Photo Viewer\\PhotoViewer.dll\", ImageView_Fullscreen " + GetKnownFolderPath(FOLDERID_Downloads) + L"\\[image name].png";
ShellExecuteW(NULL, L"open", L"rundll32.exe", cmd.c_str(), nullptr, SW_HIDE);

相关问题