You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:46:04