如何在C++中读取快捷方式文件的完整目标(含参数)
获取Windows快捷方式的完整目标路径(含参数)
你遇到的问题是IShellLink::GetPath仅返回可执行文件路径,要获取包含参数的完整原始目标,确实需要结合IShellLink::GetArguments接口实现,具体步骤如下:
- 调用
IShellLink::GetPath获取快捷指向的主可执行文件路径 - 调用
IShellLink::GetArguments提取目标路径后的参数部分 - 将主路径与参数拼接,得到完整的原始目标字符串
以下是C++实现的示例代码:
#include <windows.h> #include <shobjidl.h> #include <iostream> #include <string> std::wstring GetFullShortcutTarget(const wchar_t* shortcutPath) { HRESULT hr = CoInitialize(nullptr); if (FAILED(hr)) { return L""; } IShellLinkW* pShellLink = nullptr; hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (void**)&pShellLink); if (FAILED(hr)) { CoUninitialize(); return L""; } IPersistFile* pPersistFile = nullptr; hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile); if (FAILED(hr)) { pShellLink->Release(); CoUninitialize(); return L""; } hr = pPersistFile->Load(shortcutPath, STGM_READ); if (FAILED(hr)) { pPersistFile->Release(); pShellLink->Release(); CoUninitialize(); return L""; } // 获取主可执行文件路径 wchar_t exePath[MAX_PATH] = {0}; hr = pShellLink->GetPath(exePath, MAX_PATH, nullptr, SLGP_UNCPRIORITY); if (FAILED(hr)) { pPersistFile->Release(); pShellLink->Release(); CoUninitialize(); return L""; } // 获取参数部分 wchar_t args[MAX_PATH] = {0}; hr = pShellLink->GetArguments(args, MAX_PATH); std::wstring fullTarget = exePath; if (wcslen(args) > 0) { fullTarget += L" " + std::wstring(args); } pPersistFile->Release(); pShellLink->Release(); CoUninitialize(); return fullTarget; } int main() { const wchar_t* shortcut = L"C:\\Example\\YourShortcut.lnk"; std::wstring target = GetFullShortcutTarget(shortcut); if (!target.empty()) { std::wcout << L"完整目标:" << target << std::endl; } else { std::wcout << L"读取快捷方式失败" << std::endl; } return 0; }
注意事项
GetArguments的缓冲区大小需根据实际参数长度调整,避免参数截断- 若可执行文件路径包含空格,
GetPath返回的路径会自动添加引号,拼接参数时无需额外处理 - 编译代码时需链接
shell32.lib库
内容的提问来源于stack exchange,提问作者user23814685
相关产品推荐
相关产品推荐

