加载未定义的返回值

IPersistFile Load undefined return value

本文关键字:返回值 未定义 加载      更新时间:2023-10-16

我目前正在尝试将示例解析MSDN上的快捷方式移植到使用MinGW 4.8.1构建的QT应用程序。

我的代码(去掉了简短的错误检查)现在看起来是这样的:

QFileInfo shortcut("C:\Users\MyUserName\ShortCut.lnk");
HRESULT apiResult;
IShellLink *shellLink;
apiResult = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                             IID_IShellLink, (LPVOID*) &shellLink);
IPersistFile *persistFile;
apiResult = shellLink->QueryInterface(IID_IPersistFile, (void**) &persistFile);
WCHAR shortcutLocationWchar[MAX_PATH];
QString shortcutLocation = QDir::toNativeSeparators(shortcut.absoluteFilePath());
shortcutLocation.toWCharArray(shortcutLocationWchar);
apiResult = persistFile->Load(shortcutLocationWchar, STGM_READ);
apiResult = shellLink->Resolve(NULL, SLR_NO_UI);
WCHAR shortcutTargetWchar[MAX_PATH];
WIN32_FIND_DATA winFindData;
apiResult = shellLink->GetPath(shortcutTargetWchar, MAX_PATH, &winFindData, 0);
QString shortcutTarget = QString::fromWCharArray(shortcutTargetWchar);

目前IPersistFile::Load失败与返回值0x80070002,什么既不是在其API文档中定义,也不是winerr.h头也不是谷歌似乎提出了任何有用的结果。

有什么建议吗?

我错过了API文档中QString::toWcharArrar():

的重要一行

注意:此函数不向数组添加空字符。

所以将快捷文件名转换为WCHAR数组的正确方法是

WCHAR shortcutLocationWchar[MAX_PATH];
QString shortcutLocation = QDir::toNativeSeparators(shortcut.absoluteFilePath());
int l = shortcutLocation.toWCharArray(shortcutLocationWchar);
shortcutLocationWchar[l] = L'';

返回值0x80070002表示系统找不到指定的文件。因此你的文件路径是不正确的。我认为你应该这样写:

QFileInfo shortcut("C:\Users\MyUserName\ShortCut.lnk");

我还会以以下方式简化您的代码:

QString shortcutLocation = shortcut.absoluteFilePath();
apiResult = persistFile->Load((LPCWSTR)shortcutLocation.constData(), STGM_READ);

最后,为什么你需要使用Windows API,并将其与Qt混合,当你可以使用完全基于Qt的更简单和更短的解决方案时。例如,我将这样做:

QFileInfo shortcut(QFileInfo shortcut("D:\downloads\sk.lnk.lnk");
QString shortcutTarget ;
if (shortcut.isSymLink()) {
    shortcutTarget = shortcut.symLinkTarget();
}